Java Code Examples for org.apache.http.HttpResponse#getAllHeaders()

The following examples show how to use org.apache.http.HttpResponse#getAllHeaders() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DCContentUploader.java    From documentum-rest-client-java with Apache License 2.0 7 votes vote down vote up
public DCContentUploader upload() throws IOException
{
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", "application/octet-stream");
    post.setEntity(new InputStreamEntity(content));

    HttpResponse httpResponse = client.execute(post);
    status = httpResponse.getStatusLine().getStatusCode();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    StreamUtils.copy(httpResponse.getEntity().getContent(), os);
    response = os.toString("UTF-8");
    headers = new HttpHeaders();
    for(Header header : httpResponse.getAllHeaders()) {
        headers.add(header.getName(), header.getValue());
    }
    post.releaseConnection();
    return this;
}
 
Example 2
Source File: ResponseWrapper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public ResponseWrapper(HttpResponse response) throws OpenAS2Exception {
    super();
    setStatusCode(response.getStatusLine().getStatusCode());
    setStatusPhrase(response.getStatusLine().getReasonPhrase());

    for (org.apache.http.Header header : response.getAllHeaders()) {
        this.addHeaderLine(header.toString());
    }

    HttpEntity entity = response.getEntity();
    if (entity == null) {
        return;
    }
    byte[] data = null;
    try {
        data = EntityUtils.toByteArray(entity);
    } catch (IOException e) {
        throw new OpenAS2Exception("Failed to read response content", e);
    }
    setBody(data);
}
 
Example 3
Source File: ServiceResponseDecoder.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getHeaders(HttpResponse httpResponse) {
    Map<String, String> headers = new HashMap<>();
    Header[] responseHeaders = httpResponse.getAllHeaders();
    if (responseHeaders == null || responseHeaders.length == 0) {
        return headers;
    }
    for (Header header : responseHeaders) {
        headers.put(header.getName(), header.getValue());
        if (collectedHeaders.isEmpty()) {
            continue;
        }

        String lowerCaseHeader = header.getName().toLowerCase();
        if (collectedHeaders.containsKey(lowerCaseHeader)) {
            localCollectedHeaders.computeIfAbsent(lowerCaseHeader, s -> new ArrayList<>()).add(header.getValue());
        }
    }
    return headers;
}
 
Example 4
Source File: BasicHttpCache.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
public HttpResponse cacheAndReturnResponse(HttpHost host,
		HttpRequest request, HttpResponse originResponse, Date requestSent,
		Date responseReceived) throws IOException {

	SizeLimitedResponseReader responseReader = getResponseReader(request,
			originResponse);
	responseReader.readResponse();

	if (responseReader.isLimitReached()) {
		return responseReader.getReconstructedResponse();
	}

	Resource resource = responseReader.getResource();
	if (isIncompleteResponse(originResponse, resource)) {
		return generateIncompleteResponseError(originResponse, resource);
	}

	HttpCacheEntry entry = new HttpCacheEntry(requestSent,
			responseReceived, originResponse.getStatusLine(),
			originResponse.getAllHeaders(), resource, null);
	storeInCache(host, request, entry);
	return responseGenerator.generateResponse(entry);
}
 
Example 5
Source File: PostmanHttpResponse.java    From postman-runner with Apache License 2.0 6 votes vote down vote up
public PostmanHttpResponse(HttpResponse response) {
	this.code = response.getStatusLine().getStatusCode();

	if (code > 399) {
		logger.warn("HTTP Response code: " + code);
	}
	if (code > 499) {
		logger.error("Failed to make POSTMAN request call.");
	}

	HttpEntity entity = response.getEntity();
	if (entity != null) {
		try (InputStream resIs = entity.getContent()) {
			byte[] rawResponse = IOUtils.toByteArray(resIs);
			this.body = new String(rawResponse);
		} catch (IOException e) {
			throw new HaltTestFolderException();
		}
	}

	for (Header h : response.getAllHeaders()) {
		this.headers.put(h.getName(), h.getName());
	}
}
 
Example 6
Source File: ClientConnection.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * get a redirect for an url: this method shall be called if it is expected that a url
 * is redirected to another url. This method then discovers the redirect.
 * @param urlstring
 * @param useAuthentication
 * @return the redirect url for the given urlstring
 * @throws IOException if the url is not redirected
 */
public static String getRedirect(String urlstring) throws IOException {
    HttpGet get = new HttpGet(urlstring);
    get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
    get.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    CloseableHttpClient httpClient = getClosableHttpClient();
    HttpResponse httpResponse = httpClient.execute(get);
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        if (httpResponse.getStatusLine().getStatusCode() == 301) {
            for (Header header: httpResponse.getAllHeaders()) {
                if (header.getName().equalsIgnoreCase("location")) {
                    EntityUtils.consumeQuietly(httpEntity);
                    return header.getValue();
                }
            }
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("redirect for  " + urlstring+ ": no location attribute found");
        } else {
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("no redirect for  " + urlstring+ " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
        }
    } else {
        throw new IOException("client connection to " + urlstring + " fail: no connection");
    }
}
 
Example 7
Source File: HttpResult.java    From TvLauncher with Apache License 2.0 6 votes vote down vote up
public HttpResult(HttpResponse httpResponse, CookieStore cookieStore) {
    if (cookieStore != null) {
        this.cookies = cookieStore.getCookies().toArray(new Cookie[0]);
    }

    if (httpResponse != null) {
        this.headers = httpResponse.getAllHeaders();
        this.statuCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println(this.statuCode);
        try {
            this.response = EntityUtils.toByteArray(httpResponse.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 
Example 8
Source File: ContentTypeResourceIT.java    From usergrid with Apache License 2.0 6 votes vote down vote up
private void printResponse( HttpResponse rsp ) throws ParseException, IOException {
    HttpEntity entity = rsp.getEntity();

    System.out.println( "----------------------------------------" );
    System.out.println( rsp.getStatusLine() );

    Header[] headers = rsp.getAllHeaders();
    for ( int i = 0; i < headers.length; i++ ) {
        System.out.println( headers[i] );
    }
    System.out.println( "----------------------------------------" );

    if ( entity != null ) {
        System.out.println( EntityUtils.toString( entity ) );
    }
}
 
Example 9
Source File: PreparationGetMetadata.java    From data-prep with Apache License 2.0 6 votes vote down vote up
private ResponseEntity<DataSetMetadata> getResponseEntity(HttpStatus status, HttpResponse response) {

        final MultiValueMap<String, String> headers = new HttpHeaders();
        for (Header header : response.getAllHeaders()) {
            if (HttpHeaders.LOCATION.equalsIgnoreCase(header.getName())) {
                headers.put(header.getName(), Collections.singletonList(header.getValue()));
            }
        }
        try (final InputStream content = response.getEntity().getContent();
                final InputStreamReader contentReader = new InputStreamReader(content, UTF_8)) {
            DataSetMetadata result = objectMapper.readValue(contentReader, DataSetMetadata.class);
            return new ResponseEntity<>(result, headers, status);
        } catch (IOException e) {
            throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
        }
    }
 
Example 10
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
private static Response convert(HttpResponse response) throws IOException {
	Response res = new Response(); 
	
	if (null != response) {
		res.setStatusCode(response.getStatusLine().getStatusCode());
		for (Header header : response.getAllHeaders()) {
			res.setHeader(header.getName(), MessageDigestUtil.iso88591ToUtf8(header.getValue()));
        }
		
		res.setContentType(res.getHeader("Content-Type"));
		res.setRequestId(res.getHeader("X-Ca-Request-Id"));
		res.setErrorMessage(res.getHeader("X-Ca-Error-Message"));
		res.setBody(readStreamAsStr(response.getEntity().getContent()));
		
	} else {
		//服务器无回应
		res.setStatusCode(500);
		res.setErrorMessage("No Response");
	}
	
	return res;
}
 
Example 11
Source File: EmissaryResponse.java    From emissary with Apache License 2.0 5 votes vote down vote up
public EmissaryResponse(HttpResponse response) {
    int tempStatus = response.getStatusLine().getStatusCode();
    String tempContent;
    headers = response.getAllHeaders();
    Header[] contentHeaders = response.getHeaders(HttpHeaders.CONTENT_TYPE);
    if (contentHeaders.length > 0) {
        contentType = contentHeaders[0].getValue();
    } else if (contentHeaders.length > 1) {
        logger.warn("Too many content headers: {}", contentHeaders.length);
        if (logger.isDebugEnabled()) {
            for (int i = 0; i < contentHeaders.length; i++) {
                logger.debug("Header -> {}", contentHeaders[i]);
            }
        }
        contentType = contentHeaders[0].getValue();
    } else {
        logger.debug("No content type header, setting to plain text");
        contentType = MediaType.TEXT_PLAIN;
    }
    try {
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            logger.debug("No entity");
            tempContent = "";
        } else {
            tempContent = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8);
        }
    } catch (UnsupportedOperationException | IOException e) {
        tempContent = e.getMessage();
        tempStatus = 500;
        e.printStackTrace();
    }
    logger.debug("response was: {} with content: {}", tempStatus, tempContent);
    status = tempStatus;
    content = tempContent;
}
 
Example 12
Source File: AbstractODataResponse.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@Override
public final ODataResponse initFromHttpResponse(final HttpResponse res) {
  try {
    this.payload = res.getEntity() == null ? null : res.getEntity().getContent();
    this.inputContent = null;
  } catch (final IllegalStateException | IOException e) {
    HttpClientUtils.closeQuietly(res);
    LOG.error("Error retrieving payload", e);
    throw new ODataRuntimeException(e);
  }
  for (Header header : res.getAllHeaders()) {
    final Collection<String> headerValues;
    if (headers.containsKey(header.getName())) {
      headerValues = headers.get(header.getName());
    } else {
      headerValues = new HashSet<>();
      headers.put(header.getName(), headerValues);
    }

    headerValues.add(header.getValue());
  }

  statusCode = res.getStatusLine().getStatusCode();
  statusMessage = res.getStatusLine().getReasonPhrase();

  hasBeenInitialized = true;
  return this;
}
 
Example 13
Source File: ResponseContentSupplier.java    From service-now-plugin with MIT License 5 votes vote down vote up
private void readHeaders(HttpResponse response) {
    Header[] respHeaders = response.getAllHeaders();
    for (Header respHeader : respHeaders) {
        List<String> hs = headers.get(respHeader.getName());
        if (hs == null) {
            headers.put(respHeader.getName(), hs = new ArrayList<>());
        }
        hs.add(respHeader.getValue());
    }
}
 
Example 14
Source File: HttpPostGet.java    From ApiManager with GNU Affero General Public License v3.0 5 votes vote down vote up
private static String getHead(HttpUriRequest method, Map<String, String> headers) throws Exception {
    HttpClient client = buildHttpClient(method.getURI().getScheme());
    method.setHeader("charset", "utf-8");
    // 默认超时时间为15s。
    buildHeader(headers, method);
    HttpResponse response = client.execute(method);
    Header[] responseHeaders = response.getAllHeaders();
    StringBuilder sb = new StringBuilder("");
    for (Header h : responseHeaders) {
        sb.append(h.getName() + ":" + h.getValue() + "\r\n");
    }
    return sb.toString();
}
 
Example 15
Source File: Curl.java    From UAF with Apache License 2.0 5 votes vote down vote up
public static String post(String url, String[] header, String data) {
	String ret = "";
	try {

		HttpClient httpClient = getClient(url);

		HttpPost request = new HttpPost(url);
		if (header != null){
			for (String h : header){
				String[] split = h.split(":");
				request.addHeader(split[0], split[1]);
			}
		}
		request.setEntity(new StringEntity(data));
		try {
			HttpResponse response = httpClient.execute(request);
			ret = Curl.toStr(response);
			Header[] headers = response.getAllHeaders();

		} catch (Exception ex) {
			ex.printStackTrace();
			ret = "{'error_code':'connect_fail','url':'" + url + "'}";
		}
	} catch (Exception e) {
		e.printStackTrace();
		ret = "{'error_code':'connect_fail','e':'" + e + "'}";
	}

	return ret;
}
 
Example 16
Source File: HttpConnector.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Builds a string from given request.
 * 
 * @param message
 * @return a string from given request.
 */
private String buildResponseLogString(HttpResponse message) {
	if (message == null) {
		return "<null>";
	}

	StringBuilder result = new StringBuilder();

	if (message.getStatusLine() != null) {
		result.append(message.getStatusLine().toString()).append("\n");
	}

	if (message.getAllHeaders() != null) {
		for (Header header : message.getAllHeaders()) {
			result.append(header.toString()).append("\n");
		}
	}

	if (message instanceof BasicHttpResponse) {
		HttpEntity entity = ((BasicHttpResponse) message).getEntity();
		if (entity != null) {
			if (entity.isRepeatable()) {
				try {
					ByteArrayOutputStream entityBytes = new ByteArrayOutputStream();
					entity.writeTo(entityBytes);
					result.append(new String(entityBytes.toByteArray(), entity.getContentEncoding() == null ? charsetToUse : entity.getContentEncoding().getValue()));
				} catch (IOException e) {
					// ignore
				}
			} else {
				result.append("\n<content not repeatable>\n");
			}
		}
	}

	return result.toString();
}
 
Example 17
Source File: TestGoogleSearch.java    From albert with MIT License 4 votes vote down vote up
public static void main(String[] args) throws ClientProtocolException, IOException {
		StringBuffer sb = new StringBuffer(); 
		HttpClient client = ProxyUtil.getHttpClient();
		 HttpGet httpGet = new HttpGet(Constants.GOOGLE_SEARCH_URL+"哈哈"+"&start=1&num=10");
		 HttpResponse response = client.execute(httpGet);
		 
		 Header[] headers = response.getAllHeaders();
		 
		 if(200!=response.getStatusLine().getStatusCode()){
			  System.out.println("无法访问");
		 }
		 
		 HttpEntity entry = response.getEntity();
		 
		 if(entry != null)
		  {
		    InputStreamReader is = new InputStreamReader(entry.getContent());
		    BufferedReader br = new BufferedReader(is);
		    String str = null;
		    while((str = br.readLine()) != null)
		    {
		     sb.append(str.trim());
		    }
		    br.close();
		  }
		 
		 
		 
//		 System.out.println(sb.toString());
		  JSONArray jsonArray = null;
		  JSONObject jsonObject=null;
		  jsonArray = JSONObject.fromObject(sb.toString()).getJSONArray("items");
		  
		  GoogleSearchResult googleSearchResult =new GoogleSearchResult();
		  
		  for(int i=0,length=jsonArray.size();i<length;i++){
			  jsonObject = jsonArray.getJSONObject(i);
			  googleSearchResult.setHtmlTitle(jsonObject.getString("htmlTitle"));
			  googleSearchResult.setLink(jsonObject.getString("link"));
			  googleSearchResult.setLink(jsonObject.getString("htmlSnippet"));
			  if(jsonObject.containsKey("pagemap")&&jsonObject.getJSONObject("pagemap").containsKey("cse_thumbnail")){
				  googleSearchResult.setSrc(jsonObject.getJSONObject("pagemap").getJSONArray("cse_thumbnail").getJSONObject(0).getString("src"));
				  googleSearchResult.setWidth(jsonObject.getJSONObject("pagemap").getJSONArray("cse_thumbnail").getJSONObject(0).getString("width"));
				  googleSearchResult.setHeight(jsonObject.getJSONObject("pagemap").getJSONArray("cse_thumbnail").getJSONObject(0).getString("height"));
			  }
			  System.out.println(googleSearchResult.toString());
		  }
		 
	}
 
Example 18
Source File: HttpUtils_Deprecated.java    From UltimateAndroid with Apache License 2.0 4 votes vote down vote up
/**
 * 处理httpResponse信息,返回json,保存cookie
 *
 * @param
 * @return String
 */
public static String GetJson_Cookie(String httpUrl) {
    String strResult = null;
    try {
        // HttpGet连接对象
        HttpGet httpRequest = new HttpGet(httpUrl);
        // 取得HttpClient对象
        HttpClient httpclient = new DefaultHttpClient();
        // 请求HttpClient,取得HttpResponse
        HttpResponse httpResponse = httpclient.execute(httpRequest);
        //保存cookie
        StringBuffer sb = new StringBuffer();
        String inputLine = "";
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            Header[] hds = httpResponse.getAllHeaders();

            int isok = 0;

            for (int index = 0; index < hds.length; index++) {

                if ("Set-Cookie".equals(hds[index].getName())) {

                    String value = hds[index].getValue();

                    String[] vs = value.split(";");

                    for (int i = 0; i < vs.length; i++) {

                        String[] vss = vs[i].split("=");

                        if ("member".equals(vss[0])) {
                            rst = vs[i] + ";";
                            Log.d("Chen", "cookie信息:" + rst);
                            isok++;
                        }
                    }

                }

            }
        }

        // 请求成功
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 取得返回的字符串
            strResult = EntityUtils.toString(httpResponse.getEntity());
        } else {
            Log.i(TAG, "请求错误");
        }
    } catch (Exception e) {
        Log.i(TAG, "请求网络异常");
        strResult = "net_ex";
    }
    return strResult;
}
 
Example 19
Source File: ApacheHttpResponse.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
ApacheHttpResponse(HttpRequestBase request, HttpResponse response) {
  this.request = request;
  this.response = response;
  allHeaders = response.getAllHeaders();
}
 
Example 20
Source File: FlameUpoadUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
private static void fileUpload() throws Exception {

        file = new File("c:/Documents and Settings/dinesh/Desktop/ZShareUploaderPlugin.java");
        httpclient = new DefaultHttpClient();
//http://flameupload.com/cgi/ubr_upload.pl?upload_id=cf3feacdebff8f722a5a4051ccefda3f        
        HttpPost httppost = new HttpPost("http://flameupload.com/cgi/ubr_upload.pl?upload_id=" + uploadid);


        MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        ContentBody cbFile = new FileBody(file);

        /*
         * 
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="uploaded"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="hotfile"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="turbobit"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="depositfiles"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="fileserve"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="filefactory"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="netload"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="uploadstation"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="uploading"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="badongo"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="_2shared"
        
        on
        ------WebKitFormBoundaryyAuWHgANtPnAprcx
        Content-Disposition: form-data; name="megashare"
        
        on
        
         */


        mpEntity.addPart("upfile_0", cbFile);
        mpEntity.addPart("uploaded", new StringBody("on"));
        mpEntity.addPart("hotfile", new StringBody("on"));
        mpEntity.addPart("turbobit", new StringBody("on"));
        mpEntity.addPart("depositfiles", new StringBody("on"));
        mpEntity.addPart("fileserve", new StringBody("on"));
        mpEntity.addPart("filefactory", new StringBody("on"));
        mpEntity.addPart("netload", new StringBody("on"));
        mpEntity.addPart("uploadstation", new StringBody("on"));
        mpEntity.addPart("badongo", new StringBody("on"));
        mpEntity.addPart("uploading", new StringBody("on"));
        mpEntity.addPart("megashare", new StringBody("on"));
        mpEntity.addPart("_2shared", new StringBody("on"));

        httppost.setEntity(mpEntity);
        NULogger.getLogger().log(Level.INFO, "executing request {0}", httppost.getRequestLine());
        NULogger.getLogger().info("Now uploading your file into flameupload.com");
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        NULogger.getLogger().info(response.getStatusLine().toString());
        NULogger.getLogger().info(EntityUtils.toString(resEntity));
        Header[] allHeaders = response.getAllHeaders();
        for (int i = 0; i < allHeaders.length; i++) {
            System.out.println(allHeaders[i].getName() + "=" + allHeaders[i].getValue());
        }

        if (response.getStatusLine().getStatusCode() == 302) {
            NULogger.getLogger().info("Files uploaded successfully");
        } else {
            throw new Exception("There might be a problem with your internet connection or server error. Please try again later :(");
        }

    }