本文整理了Java中org.apache.http.client.HttpClient
类的一些代码示例,展示了HttpClient
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpClient
类的具体详情如下:
包路径:org.apache.http.client.HttpClient
类名称:HttpClient
[英]Interface for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.
[中]HTTP客户端的接口。HTTP客户端封装了执行HTTP请求所需的大量对象,同时处理cookie、身份验证、连接管理和其他功能。HTTP客户端的线程安全取决于特定客户端的实现和配置。
代码示例来源:origin: stackoverflow.com
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) // Read line by line
sb.append(line + "\n");
String resString = sb.toString(); // Result is here
is.close(); // Close the stream
代码示例来源:origin: stackoverflow.com
public void callRestWebService(){
System.out.println(".....REST..........");
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(wsdlURL);
request.addHeader("company name", "abc");
request.addHeader("getAccessNumbers","http://service.xyz.com/");
ResponseHandler<String> handler = new BasicResponseHandler();
try {
result = httpclient.execute(request, handler);
System.out.println("..result..."+result);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpclient.getConnectionManager().shutdown();
} // end callWebService()
}
代码示例来源:origin: stackoverflow.com
JSONObject resultJson = new JSONObject(resultJsonString);
String blobKey = resultJson.getString("blobKey");
String servingUrl = resultJson.getString("servingUrl");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userId", userId));
nameValuePairs.add(new BasicNameValuePair("blobKey",blobKey));
nameValuePairs.add(new BasicNameValuePair("servingUrl",servingUrl));
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000);
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
// Continue to store the (immediately available) serving url in local storage f.ex
代码示例来源:origin: stackoverflow.com
HttpClient httpclient = new HttpClient();
httpclient.getParams().setParameter(
HttpMethodParams.USER_AGENT,
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"
);
代码示例来源:origin: stackoverflow.com
HttpClient httpclient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000); //Timeout Limit
HttpGet httpGet = new HttpGet("http://example.com/blob/getuploadurl");
response = httpclient.execute(httpGet);
代码示例来源:origin: opentripplanner/OpenTripPlanner
/** Get the AWS instance type if applicable */
public String getInstanceType () {
try {
HttpGet get = new HttpGet();
// see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html
// This seems very much not EC2-like to hardwire an IP address for getting instance metadata,
// but that's how it's done.
get.setURI(new URI("http://169.254.169.254/latest/meta-data/instance-type"));
get.setConfig(RequestConfig.custom()
.setConnectTimeout(2000)
.setSocketTimeout(2000)
.build()
);
HttpResponse res = httpClient.execute(get);
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String type = reader.readLine().trim();
reader.close();
return type;
} catch (Exception e) {
LOG.info("could not retrieve EC2 instance type, you may be running outside of EC2.");
return null;
}
}
代码示例来源:origin: stackoverflow.com
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
代码示例来源:origin: stackoverflow.com
BufferedReader br = new BufferedReader(new InputStreamReader(is));
for (String line = br.readLine(); line != null; line = br.readLine())
out.append(line);
br.close();
new SecureRandom());
HttpClient client = new DefaultHttpClient();
ClientConnectionManager ccm = client.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
DefaultHttpClient sslClient = new DefaultHttpClient(ccm,
client.getParams());
HttpGet get = new HttpGet(new URI(url));
HttpResponse response = sslClient.execute(get);
代码示例来源:origin: stackoverflow.com
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(uri);
httpget.setHeader("User-Agent", userAgent);
HttpResponse response = httpclient.execute(httpget, localContext);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
InputStream instream = entity.getContent();
String videoInfo = getStringFromInputStream(encoding, instream);
if (videoInfo != null && videoInfo.length() > 0) {
HttpGet httpget2 = new HttpGet(downloadUrl);
httpget2.setHeader("User-Agent", userAgent);
log.finer("Executing " + httpget2.getURI());
HttpClient httpclient2 = new DefaultHttpClient();
HttpResponse response2 = httpclient2.execute(httpget2);
HttpEntity entity2 = response2.getEntity();
if (entity2 != null && response2.getStatusLine().getStatusCode() == 200) {
long length = entity2.getContentLength();
InputStream instream2 = entity2.getContent();
log.finer("Writing " + length + " bytes to " + outputfile);
if (outputfile.exists()) {
代码示例来源:origin: apache/metron
public String getRESTJSONResults(URL endpointUrl, Map<String, String> getArgs) throws IOException, URISyntaxException { String encodedParams = encodeParams(getArgs);
HttpGet get = new HttpGet(appendToUrl(endpointUrl, encodedParams).toURI());
get.addHeader("accept", "application/json");
HttpResponse response = CLIENT.get().execute(get);
if (response.getStatusLine().getStatusCode() != 200) {
throw new IllegalStateException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
return new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
.lines().collect(Collectors.joining("\n"));
}
public URL appendToUrl(URL endpointUrl, String params) throws MalformedURLException {
代码示例来源:origin: stackoverflow.com
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://download.finance.yahoo.com/d/quotes.csv?s=msft&f=sl1p2");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()
)
);
代码示例来源:origin: pentaho/pentaho-kettle
HttpGet getMethod = new HttpGet( urlAsString );
if ( !Utils.isEmpty( username ) ) {
HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
httpClient = HttpClientManager.getInstance().createDefaultClient();
HttpResponse httpResponse = httpClient.execute( getMethod );
int statusCode = httpResponse.getStatusLine().getStatusCode();
StringBuilder bodyBuffer = new StringBuilder();
if ( statusCode != HttpStatus.SC_UNAUTHORIZED ) {
InputStreamReader inputStreamReader = new InputStreamReader( httpResponse.getEntity().getContent() );
while ( ( c = inputStreamReader.read() ) != -1 ) {
bodyBuffer.append( (char) c );
inputStreamReader.close();
代码示例来源:origin: neo4j/neo4j
@Test
public void shouldParameteriseUrisInRelationshipRepresentationWithoutHostHeaderUsingRequestUri() throws Exception
{
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( getServerUri() + "db/data/relationship/" + likes );
httpget.setHeader( "Accept", "application/json" );
HttpResponse response = httpclient.execute( httpget );
HttpEntity entity = response.getEntity();
String entityBody = IOUtils.toString( entity.getContent(), StandardCharsets.UTF_8 );
assertThat( entityBody, containsString( getServerUri() + "db/data/relationship/" + likes ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
代码示例来源:origin: opentripplanner/OpenTripPlanner
public static InputStream getData(String url, String requestHeaderName, String requestHeaderValue) throws ClientProtocolException, IOException {
HttpGet httpget = new HttpGet(url);
if (requestHeaderValue != null) {
httpget.addHeader(requestHeaderName, requestHeaderValue);
}
HttpClient httpclient = getClient();
HttpResponse response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() != 200)
return null;
HttpEntity entity = response.getEntity();
if (entity == null) {
return null;
}
return entity.getContent();
}
代码示例来源:origin: stackoverflow.com
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
代码示例来源:origin: apache/nifi
private JSONObject readJSONObjectFromUrlPOST(String urlString, Map<String, String> headers, String payload) throws IOException, JSONException {
HttpClient httpClient = openConnection();
HttpPost request = new HttpPost(urlString);
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
HttpEntity httpEntity = new StringEntity(payload);
request.setEntity(httpEntity);
HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase());
}
InputStream content = response.getEntity().getContent();
return readAllIntoJSONObject(content);
}
代码示例来源:origin: jiangqqlmj/FastDev4Android
HttpPost httpPost = null;
URI encodedUri = getEncodingURI(url);
httpPost = new HttpPost(encodedUri);
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, DELIVER_CONN_TIMEOUT);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
DELIVER_SOCKET_TIMEOUT);
try {
nameValuePair.add(basicNameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,
HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null) {
int code = httpResponse.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK) {
Log.d(TAG_LISTLOGIC, "post投递服务器返回200");
return;
} else {
httpPost.abort();
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
httpClient = null;
代码示例来源:origin: shuzheng/zheng
HttpPost httpPost = null;
try {
HttpClient httpClient = new DefaultHttpClient();
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json; charset=utf-8");
httpPost.setEntity(httpEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
String result = EntityUtils.toString(resEntity, Charset.forName("utf-8"));
代码示例来源:origin: stackoverflow.com
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
File file = new File("c:/TRASH/zaba_1.jpg");
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
resEntity.consumeContent();
httpclient.getConnectionManager().shutdown();
代码示例来源:origin: jiangqqlmj/FastDev4Android
try {
encodedUri = new URI(url);
httpGet = new HttpGet(encodedUri);
} catch (URISyntaxException e) {
httpGet = new HttpGet(encodedUrl);
e.printStackTrace();
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
5000);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse != null) {
int uRC = httpResponse.getStatusLine().getStatusCode();
if (uRC == HttpStatus.SC_OK) {
return true;
} else {
httpGet.abort();
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
httpClient = null;
内容来源于网络,如有侵权,请联系作者删除!