• 关于

    apache httpclient api

    的搜索结果

问题

android api23 抛弃了httpClient基于httpClient第三方库如何处理?

蛮大人123 2019-12-01 19:59:24 1218 浏览量 回答数 1

回答

全面部分都ok,可是 PutObjectFromFile !!!初始变量 static String upFilePath = "g:/alidata/updata/up.rar";     static String downFilePath = "g:/alidata/downdata/down.rar";     static String bucket = accessKeyId.toLowerCase() +"-test-buchet";     static String object = accessKeyId.toLowerCase() + "-test-object";     static String group = accessKeyId.toLowerCase() + "-test-group"; ----- GettObjectWithIfMatch ------ Success ----- GetObjectInputStream ------ OSS Sample ----- GetObjectInputStreamWithRange ------ Date:Mon, 21 Nov 2011 08:05:56 GMT Server:AliyunOSS x-oss-request-id:2a5bd7f2-6698-e261-387c-f2877a6c7b52 Last-Modified:Mon, 21 Nov 2011 08:05:56 GMT ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Connection:close Accept-Ranges:bytes Content-Range:bytes 0-5/10 Content-Length:6 Content-Type:text/plain OSS Sa ----- PutObjectWithUserMeta------ Success ----- GetObjectMeta ----- x-oss-request-id:5a4cc6b4-645c-8bc4-2b83-f8b95b63a452 ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Date:Mon, 21 Nov 2011 08:06:19 GMT Content-Length:10 Last-Modified:Mon, 21 Nov 2011 08:06:16 GMT x-oss-meta-id:123 Content-Type:text/plain Connection:close Server:AliyunOSS ----- IsObjectExists ----- true ----- PutObjectFromFile ----- 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.SocketException) caught when processing request: Software caused connection abort: socket write error 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request Exception in thread "main" org.apache.commons.httpclient.ProtocolException: Unbuffered entity enclosing request can not be repeated.     at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:487)     at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)     at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)     at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)     at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)     at com.aliyun.oss.api.OSSClient.execute(OSSClient.java:130)     at com.aliyun.oss.api.OSSClient.request(OSSClient.java:168)     at com.aliyun.oss.api.OSSClient.objectOperation(OSSClient.java:206)     at com.aliyun.oss.api.OSSClient.putObjectFromInputStream(OSSClient.java:829)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:775)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:745)     at OssSample.main(OssSample.java:219)

cube3power 2019-12-02 02:41:03 0 浏览量 回答数 0

回答

全面部分都ok,可是 PutObjectFromFile !!!初始变量 static String upFilePath = "g:/alidata/updata/up.rar";     static String downFilePath = "g:/alidata/downdata/down.rar";     static String bucket = accessKeyId.toLowerCase() +"-test-buchet";     static String object = accessKeyId.toLowerCase() + "-test-object";     static String group = accessKeyId.toLowerCase() + "-test-group"; ----- GettObjectWithIfMatch ------ Success ----- GetObjectInputStream ------ OSS Sample ----- GetObjectInputStreamWithRange ------ Date:Mon, 21 Nov 2011 08:05:56 GMT Server:AliyunOSS x-oss-request-id:2a5bd7f2-6698-e261-387c-f2877a6c7b52 Last-Modified:Mon, 21 Nov 2011 08:05:56 GMT ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Connection:close Accept-Ranges:bytes Content-Range:bytes 0-5/10 Content-Length:6 Content-Type:text/plain OSS Sa ----- PutObjectWithUserMeta------ Success ----- GetObjectMeta ----- x-oss-request-id:5a4cc6b4-645c-8bc4-2b83-f8b95b63a452 ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Date:Mon, 21 Nov 2011 08:06:19 GMT Content-Length:10 Last-Modified:Mon, 21 Nov 2011 08:06:16 GMT x-oss-meta-id:123 Content-Type:text/plain Connection:close Server:AliyunOSS ----- IsObjectExists ----- true ----- PutObjectFromFile ----- 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.SocketException) caught when processing request: Software caused connection abort: socket write error 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request Exception in thread "main" org.apache.commons.httpclient.ProtocolException: Unbuffered entity enclosing request can not be repeated.     at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:487)     at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)     at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)     at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)     at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)     at com.aliyun.oss.api.OSSClient.execute(OSSClient.java:130)     at com.aliyun.oss.api.OSSClient.request(OSSClient.java:168)     at com.aliyun.oss.api.OSSClient.objectOperation(OSSClient.java:206)     at com.aliyun.oss.api.OSSClient.putObjectFromInputStream(OSSClient.java:829)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:775)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:745)     at OssSample.main(OssSample.java:219)

cube3power 2019-12-02 02:37:59 0 浏览量 回答数 0

阿里云高校特惠,助力学生创业梦!0元体验,快速入门云计算!

学生动手场景应用,快速了解并掌握云服务器的各种新奇玩法!

回答

全面部分都ok,可是 PutObjectFromFile !!!初始变量 static String upFilePath = "g:/alidata/updata/up.rar";     static String downFilePath = "g:/alidata/downdata/down.rar";     static String bucket = accessKeyId.toLowerCase() +"-test-buchet";     static String object = accessKeyId.toLowerCase() + "-test-object";     static String group = accessKeyId.toLowerCase() + "-test-group"; ----- GettObjectWithIfMatch ------ Success ----- GetObjectInputStream ------ OSS Sample ----- GetObjectInputStreamWithRange ------ Date:Mon, 21 Nov 2011 08:05:56 GMT Server:AliyunOSS x-oss-request-id:2a5bd7f2-6698-e261-387c-f2877a6c7b52 Last-Modified:Mon, 21 Nov 2011 08:05:56 GMT ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Connection:close Accept-Ranges:bytes Content-Range:bytes 0-5/10 Content-Length:6 Content-Type:text/plain OSS Sa ----- PutObjectWithUserMeta------ Success ----- GetObjectMeta ----- x-oss-request-id:5a4cc6b4-645c-8bc4-2b83-f8b95b63a452 ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Date:Mon, 21 Nov 2011 08:06:19 GMT Content-Length:10 Last-Modified:Mon, 21 Nov 2011 08:06:16 GMT x-oss-meta-id:123 Content-Type:text/plain Connection:close Server:AliyunOSS ----- IsObjectExists ----- true ----- PutObjectFromFile ----- 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.SocketException) caught when processing request: Software caused connection abort: socket write error 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request Exception in thread "main" org.apache.commons.httpclient.ProtocolException: Unbuffered entity enclosing request can not be repeated.     at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:487)     at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)     at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)     at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)     at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)     at com.aliyun.oss.api.OSSClient.execute(OSSClient.java:130)     at com.aliyun.oss.api.OSSClient.request(OSSClient.java:168)     at com.aliyun.oss.api.OSSClient.objectOperation(OSSClient.java:206)     at com.aliyun.oss.api.OSSClient.putObjectFromInputStream(OSSClient.java:829)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:775)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:745)     at OssSample.main(OssSample.java:219)

cube3power 2019-12-02 02:39:59 0 浏览量 回答数 0

回答

全面部分都ok,可是 PutObjectFromFile !!!初始变量 static String upFilePath = "g:/alidata/updata/up.rar";     static String downFilePath = "g:/alidata/downdata/down.rar";     static String bucket = accessKeyId.toLowerCase() +"-test-buchet";     static String object = accessKeyId.toLowerCase() + "-test-object";     static String group = accessKeyId.toLowerCase() + "-test-group"; ----- GettObjectWithIfMatch ------ Success ----- GetObjectInputStream ------ OSS Sample ----- GetObjectInputStreamWithRange ------ Date:Mon, 21 Nov 2011 08:05:56 GMT Server:AliyunOSS x-oss-request-id:2a5bd7f2-6698-e261-387c-f2877a6c7b52 Last-Modified:Mon, 21 Nov 2011 08:05:56 GMT ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Connection:close Accept-Ranges:bytes Content-Range:bytes 0-5/10 Content-Length:6 Content-Type:text/plain OSS Sa ----- PutObjectWithUserMeta------ Success ----- GetObjectMeta ----- x-oss-request-id:5a4cc6b4-645c-8bc4-2b83-f8b95b63a452 ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Date:Mon, 21 Nov 2011 08:06:19 GMT Content-Length:10 Last-Modified:Mon, 21 Nov 2011 08:06:16 GMT x-oss-meta-id:123 Content-Type:text/plain Connection:close Server:AliyunOSS ----- IsObjectExists ----- true ----- PutObjectFromFile ----- 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.SocketException) caught when processing request: Software caused connection abort: socket write error 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request Exception in thread "main" org.apache.commons.httpclient.ProtocolException: Unbuffered entity enclosing request can not be repeated.     at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:487)     at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)     at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)     at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)     at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)     at com.aliyun.oss.api.OSSClient.execute(OSSClient.java:130)     at com.aliyun.oss.api.OSSClient.request(OSSClient.java:168)     at com.aliyun.oss.api.OSSClient.objectOperation(OSSClient.java:206)     at com.aliyun.oss.api.OSSClient.putObjectFromInputStream(OSSClient.java:829)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:775)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:745)     at OssSample.main(OssSample.java:219)

cube3power 2019-12-02 02:38:59 0 浏览量 回答数 0

回答

全面部分都ok,可是 PutObjectFromFile !!!初始变量 static String upFilePath = "g:/alidata/updata/up.rar";     static String downFilePath = "g:/alidata/downdata/down.rar";     static String bucket = accessKeyId.toLowerCase() +"-test-buchet";     static String object = accessKeyId.toLowerCase() + "-test-object";     static String group = accessKeyId.toLowerCase() + "-test-group"; ----- GettObjectWithIfMatch ------ Success ----- GetObjectInputStream ------ OSS Sample ----- GetObjectInputStreamWithRange ------ Date:Mon, 21 Nov 2011 08:05:56 GMT Server:AliyunOSS x-oss-request-id:2a5bd7f2-6698-e261-387c-f2877a6c7b52 Last-Modified:Mon, 21 Nov 2011 08:05:56 GMT ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Connection:close Accept-Ranges:bytes Content-Range:bytes 0-5/10 Content-Length:6 Content-Type:text/plain OSS Sa ----- PutObjectWithUserMeta------ Success ----- GetObjectMeta ----- x-oss-request-id:5a4cc6b4-645c-8bc4-2b83-f8b95b63a452 ETag:"9BF156C2C16BB90B9EC81C96FE37EF1B" Date:Mon, 21 Nov 2011 08:06:19 GMT Content-Length:10 Last-Modified:Mon, 21 Nov 2011 08:06:16 GMT x-oss-meta-id:123 Content-Type:text/plain Connection:close Server:AliyunOSS ----- IsObjectExists ----- true ----- PutObjectFromFile ----- 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: I/O exception (java.net.SocketException) caught when processing request: Software caused connection abort: socket write error 2011-11-21 16:23:11 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry 信息: Retrying request Exception in thread "main" org.apache.commons.httpclient.ProtocolException: Unbuffered entity enclosing request can not be repeated.     at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:487)     at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)     at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)     at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)     at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)     at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)     at com.aliyun.oss.api.OSSClient.execute(OSSClient.java:130)     at com.aliyun.oss.api.OSSClient.request(OSSClient.java:168)     at com.aliyun.oss.api.OSSClient.objectOperation(OSSClient.java:206)     at com.aliyun.oss.api.OSSClient.putObjectFromInputStream(OSSClient.java:829)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:775)     at com.aliyun.oss.api.OSSClient.putObjectFromFile(OSSClient.java:745)     at OssSample.main(OssSample.java:219)

cube3power 2019-12-02 02:36:54 0 浏览量 回答数 0

回答

package com.example.testjsonandget;import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.params.HttpClientParams;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpConnectionParams;import org.apache.http.params.HttpParams;import org.json.JSONArray;import org.json.JSONObject; import android.app.Activity;import android.os.Bundle; public class MainActivity extends Activity { private final String uriString="your url"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //服务器返回的JSON数据 JSONObject jsonObject=this.getJSONObjectByGet(); try { //从JSON中得到字符串 String apiString=jsonObject.getString("api"); String countString=jsonObject.getString("count"); System.out.println("apiString="+apiString+",countString="+countString); //从JSON中得到JSONArray,并且遍历 JSONArray jsonArray=jsonObject.getJSONArray("data"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject everyJsonObject=jsonArray.getJSONObject(i); String category_id=everyJsonObject.getString("category_id"); String category_name=everyJsonObject.getString("category_name"); String category_rgb=everyJsonObject.getString("category_rgb"); String category_news_count=everyJsonObject.getString("category_news_count"); System.out.println("category_id="+category_id+",category_name="+category_name+ ",category_rgb="+category_rgb+",category_news_count="+category_news_count); System.out.println("====================================================="); } } catch (Exception e) { e.printStackTrace(); } } //得到HttpClient public HttpClient getHttpClient(){ HttpParams mHttpParams=new BasicHttpParams(); //设置网络链接超时 //即:Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(mHttpParams, 20*1000); //设置socket响应超时 //即:in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(mHttpParams, 20*1000); //设置socket缓存大小 HttpConnectionParams.setSocketBufferSize(mHttpParams, 8*1024); //设置是否可以重定向 HttpClientParams.setRedirecting(mHttpParams, true); HttpClient httpClient=new DefaultHttpClient(mHttpParams); return httpClient; } //得到JSONObject(Get方式) public JSONObject getJSONObjectByGet(){ JSONObject resultJsonObject=null; if ("".equals(uriString)||uriString==null) { return null; } HttpClient httpClient=this.getHttpClient(); StringBuilder urlStringBuilder=new StringBuilder(uriString); StringBuilder entityStringBuilder=new StringBuilder(); //利用URL生成一个HttpGet请求 HttpGet httpGet=new HttpGet(urlStringBuilder.toString()); BufferedReader bufferedReader=null; HttpResponse httpResponse=null; try { //HttpClient发出一个HttpGet请求 httpResponse=httpClient.execute(httpGet); } catch (Exception e) { e.printStackTrace(); } //得到httpResponse的状态响应码 int statusCode=httpResponse.getStatusLine().getStatusCode(); if (statusCode==HttpStatus.SC_OK) { //得到httpResponse的实体数据 HttpEntity httpEntity=httpResponse.getEntity(); if (httpEntity!=null) { try { bufferedReader=new BufferedReader (new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024); String line=null; while ((line=bufferedReader.readLine())!=null) { entityStringBuilder.append(line+"/n"); } //利用从HttpEntity中得到的String生成JsonObject resultJsonObject=new JSONObject(entityStringBuilder.toString()); } catch (Exception e) { e.printStackTrace(); } } } return resultJsonObject; } //----------------------------------------以下为POST请求 //准备进行POST请求的参数,一般而言将这些参数封装在HashMap中 public JSONObject save(String title, String timelength) throws Exception{ Map<String,String> paramsHashMap = new HashMap<String, String>(); paramsHashMap.put("title", title); paramsHashMap.put("timelength", timelength); paramsHashMap.put("method", "save"); String path = "your url"; return getJSONObjectByPost(path, paramsHashMap, "UTF-8"); } //得到JSONObject(Post方式) //此方法此处未调用测试 public JSONObject getJSONObjectByPost(String path,Map<String, String> paramsHashMap, String encoding) { JSONObject resultJsonObject = null; List<NameValuePair> nameValuePairArrayList = new ArrayList<NameValuePair>(); // 将传过来的参数填充到List<NameValuePair>中 if (paramsHashMap != null && !paramsHashMap.isEmpty()) { for (Map.Entry<String, String> entry : paramsHashMap.entrySet()) { nameValuePairArrayList.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } UrlEncodedFormEntity entity = null; try { // 利用List<NameValuePair>生成Post请求的实体数据 // 此处使用了UrlEncodedFormEntity!!! entity = new UrlEncodedFormEntity(nameValuePairArrayList, encoding); HttpPost httpPost = new HttpPost(path); // 为HttpPost设置实体数据 httpPost.setEntity(entity); HttpClient httpClient = this.getHttpClient(); // HttpClient发出Post请求 HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { // 得到httpResponse的实体数据 HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { try { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpEntity.getContent(),"UTF-8"), 8 * 1024); StringBuilder entityStringBuilder = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { entityStringBuilder.append(line + "/n"); } // 利用从HttpEntity中得到的String生成JsonObject resultJsonObject = new JSONObject(entityStringBuilder.toString()); } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { e.printStackTrace(); } return resultJsonObject; } } ps:来源网络

元芳啊 2019-12-02 00:54:42 0 浏览量 回答数 0

问题

webservice接口,报Connection timed out: connect?报错

爱吃鱼的程序员 2020-06-08 20:44:41 0 浏览量 回答数 1

回答

我这段代码是没问题的:addBinaryBody方法的第一个字段就是表单项,不能同名。 import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.http.entity.mime.MultipartEntityBuilder; import java.io.File; public class UploadFileTest { public static void main(String[] args) throws Exception { File file1 = new File("D:\\images\\assets\\headImgs\\head_0.png"); File file2 = new File("D:\\images\\assets\\headImgs\\head_1.png"); File file3 = new File("D:\\images\\assets\\headImgs\\head_2.png"); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://127.0.0.1:80/upload"); HttpEntity reqEntity = MultipartEntityBuilder.create() .addTextBody("status", "这是一条来自java后台的测试微博,文本中必须包含至少一个第三方分享到微博的网页URL,并且字数不能超过140字。http://www.baidu.com") .addBinaryBody("img1", file1, ContentType.IMAGE_PNG, file1.getName()) .addBinaryBody("img2", file2, ContentType.IMAGE_PNG, file2.getName()) .addBinaryBody("img3", file3, ContentType.IMAGE_PNG, file3.getName()) .addTextBody("access_token", "2.00yOFlzGV4RsoDf88fdf1a7fINBEJB") .build(); httpPost.setEntity(reqEntity); try { CloseableHttpResponse response = httpclient.execute(httpPost); try { int code = response.getStatusLine().getStatusCode(); String info = response.getStatusLine().getReasonPhrase(); if(code != 200) { throw new Exception(String.valueOf(code) + "&" + info); } System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } } }  ######回复 @银杏卡卡 : 谢谢你耐心回复 我在微博开放平台17年的公告下面的网友评论里找到了 确实只能上传一张图片 这个API文档都没人维护更新 很气人 浪费了大量时间######回复 @泽西岛屿 : 图片看不到######回复 @银杏卡卡 : 我提问的那个截图就是微博API对于发布图文微博的介绍 有点迷茫 没说可以多图也没说不可以 按照他的字段格式提交多图微博的请求却只有一个图片######回复 @泽西岛屿 : 我没弄过这种,微博提供的接口文档有介绍没?是否支持多文件上传呢?如果是那边不支持你们也没办法,直接pass掉好了######回复 @银杏卡卡 : 很苦恼啊 循环多次就变成了多条微博 项目要求是一条微博配多图 有点难受###### 用HttpClient不是很简单吗###### package org.apache.http.examples.entity.mime; import java.io.File; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * Example how to use multipart/form encoded POST request. */ public class ClientMultipartFormPost { public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("File path not given"); System.exit(1); } CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample"); FileBody bin = new FileBody(new File(args[0])); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("bin", bin) .addPart("comment", comment) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } } } HttpClient官方例子:  ######代码在下边,求指教######因为发布图文微博 微博要求图片上传格式是binary 我用的MultipartEntityBuilder和CloseableHttpClient 但是现在只能上传一张图片 不知道怎么传多图######单张图片的很简单 已经实现了 发布多图微博的时候只能传一张图片 不知道有没有什么好方法###### package com.aaa; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.EntityUtils; public class weibo { public static void main(String[] args) throws Exception { File file = new File("E:\\article\\weibo_20190114161835827.jpeg"); File file1 = new File("E:\\article\\weibo_20190114161836750.jpeg"); File file2 = new File("E:\\article\\weibo_20190114161837173.jpeg"); File file3 = new File("E:\\article\\weibo_20190114161837190.jpeg"); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://api.weibo.com/2/statuses/share.json"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); ContentType strContent = ContentType.create("text/plain",Charset.forName("UTF-8")); ContentType imageContent = ContentType.create("image/jpeg"); builder.addTextBody("status", "这是一条来自java后台的测试微博,文本中必须包含至少一个第三方分享到微博的网页URL,并且字数不能超过140字。http://www.baidu.com", strContent); builder.addBinaryBody("pic", file,imageContent, file.getName()); builder.addBinaryBody("pic", file1,imageContent, file1.getName()); builder.addBinaryBody("pic", file2,imageContent, file2.getName()); builder.addBinaryBody("pic", file3,imageContent, file3.getName()); builder.addTextBody("access_token", "2.00yOFlzGV4RsoDf88fdf1a7fINBEJB"); // builder.addBinaryBody("name=\"pic\"; filename=\"weibo_20190114161835827.jpeg\"", new File("E:\\article\\weibo_20190114161835827.jpeg")); // builder.addBinaryBody("name=\"pic\"; filename=\"weibo_20190114161835827.jpeg\"", new File("E:\\article\\weibo_20190114161835827.jpeg")); HttpEntity parameterEntity = builder.build(); httpPost.setEntity(parameterEntity); CloseableHttpResponse response = httpclient.execute(httpPost); if (response.getCode() != 200) { throw new Exception(String.valueOf(response.getCode()) + "&" + response.getReasonPhrase()); } HttpEntity resultEntity = response.getEntity(); if (resultEntity == null) { throw new Exception("response null"); } String result = EntityUtils.toString(resultEntity); System.out.println("微博发送完毕:" + result); } }  

爱吃鱼的程序员 2020-06-02 17:24:17 0 浏览量 回答数 0

问题

使用HTTPDNS如何解决HTTPS的问题?

下班我不走 2019-12-01 19:52:17 1413 浏览量 回答数 0

回答

:拿到JAVA API后,为什么运行例子之后报错? run: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Uncompilable source code - package org.apache.commons.httpclient does not exist     at OssTest.<clinit>(OssTest.java:9) Exception in thread "main" Java Result: 1 成功生成(总时间:1 秒)

ericg 2019-12-02 02:43:52 0 浏览量 回答数 0

回答

:拿到JAVA API后,为什么运行例子之后报错? run: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Uncompilable source code - package org.apache.commons.httpclient does not exist     at OssTest.<clinit>(OssTest.java:9) Exception in thread "main" Java Result: 1 成功生成(总时间:1 秒)

ericg 2019-12-02 02:44:41 0 浏览量 回答数 0

回答

:拿到JAVA API后,为什么运行例子之后报错? run: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Uncompilable source code - package org.apache.commons.httpclient does not exist     at OssTest.<clinit>(OssTest.java:9) Exception in thread "main" Java Result: 1 成功生成(总时间:1 秒)

ericg 2019-12-02 02:46:15 0 浏览量 回答数 0

回答

:拿到JAVA API后,为什么运行例子之后报错? run: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Uncompilable source code - package org.apache.commons.httpclient does not exist     at OssTest.<clinit>(OssTest.java:9) Exception in thread "main" Java Result: 1 成功生成(总时间:1 秒)

ericg 2019-12-02 02:43:02 0 浏览量 回答数 0

回答

:拿到JAVA API后,为什么运行例子之后报错? run: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Uncompilable source code - package org.apache.commons.httpclient does not exist     at OssTest.<clinit>(OssTest.java:9) Exception in thread "main" Java Result: 1 成功生成(总时间:1 秒)

ericg 2019-12-02 02:45:30 0 浏览量 回答数 0

回答

:拿到JAVA API后,为什么运行例子之后报错? run: java.lang.ExceptionInInitializerError Caused by: java.lang.RuntimeException: Uncompilable source code - package org.apache.commons.httpclient does not exist     at OssTest.<clinit>(OssTest.java:9) Exception in thread "main" Java Result: 1 成功生成(总时间:1 秒)

ericg 2019-12-02 02:42:04 0 浏览量 回答数 0

回答

可以试试如下解决方法: 1.调整Tomcat对应类的log级别修改${tomcat}/conf/log4j.properties##解除类org.apache.jasper.compiler.TldLocationsCache的logorg.apache.jasper.compiler.TldLocationsCache.level=FINE  2.观察Tomcat日志打印信息步骤1执行完后,重启Tomcat,观察Tomcat日志,会在日志中发现类似如下打印信息:九月09,201310:55:37上午org.apache.jasper.compiler.TldLocationsCachetldScanJar详细:NoTLDfileswerefoundin[file:/E:/devspace/xxt_login/WEB-INF/lib/json-lib-2.3-jdk15.jar].ConsideraddingtheJARtothetomcat.util.scan.DefaultJarScanner.jarsToSkipororg.apache.catalina.startup.TldConfig.jarsToSkippropertyinCATALINA_BASE/conf/catalina.propertiesfile.九月09,201310:55:37上午org.apache.jasper.compiler.TldLocationsCachetldScanJar详细:NoTLDfileswerefoundin[file:/E:/devspace/xxt_login/WEB-INF/lib/poi-3.8.jar].ConsideraddingtheJARtothetomcat.util.scan.DefaultJarScanner.jarsToSkipororg.apache.catalina.startup.TldConfig.jarsToSkippropertyinCATALINA_BASE/conf/catalina.propertiesfile.  3.调整${tomcat}/conf/catalina.properties,将提示的jar添加到不扫描清单中tomcat.util.scan.DefaultJarScanner.jarsToSkip=<br/>bootstrap.jar,commons-daemon.jar,tomcat-juli.jar,<br/>annotations-api.jar,el-api.jar,jsp-api.jar,servlet-api.jar,<br/>catalina.jar,catalina-ant.jar,catalina-ha.jar,catalina-tribes.jar,<br/>jasper.jar,jasper-el.jar,ecj-.jar,<br/>tomcat-api.jar,tomcat-util.jar,tomcat-coyote.jar,tomcat-dbcp.jar,<br/>tomcat-jni.jar,tomcat-spdy.jar,<br/>tomcat-i18n-en.jar,tomcat-i18n-es.jar,tomcat-i18n-fr.jar,tomcat-i18n-ja.jar,<br/>tomcat-juli-adapters.jar,catalina-jmx-remote.jar,catalina-ws.jar,<br/>tomcat-jdbc.jar,<br/>tools.jar,<br/>commons-beanutils.jar,commons-codec*.jar,commons-collections*.jar,<br/>commons-dbcp*.jar,commons-digester*.jar,commons-fileupload*.jar,<br/>commons-httpclient*.jar,commons-io*.jar,commons-lang*.jar,commons-logging*.jar,<br/>commons-math*.jar,commons-pool*.jar,<br/>jstl.jar,<br/>geronimo-spec-jaxrpc*.jar,wsdl4j*.jar,<br/>ant.jar,ant-junit*.jar,aspectj*.jar,jmx.jar,h2*.jar,hibernate*.jar,httpclient*.jar,<br/>jmx-tools.jar,jta*.jar,log4j*.jar,mail*.jar,slf4j*.jar,<br/>xercesImpl.jar,xmlParserAPIs.jar,xml-apis.jar,<br/>junit.jar,junit-.jar,ant-launcher.jar,<br/>json-lib-.jar,poi-.jar  【注意】1.如果使用eclipseserver插件、Sysdeotomcat插件启动Tomcat,此配合可能无效2.步骤1调整完后,最好清除下以下两个文件夹${tomcat}/conf/Catalina${tomcat}/work/Catalina3.尽量使用号实现模式匹配,以避免因jar版本升级带来的重复修改代价 <spanstyle="color:#454545;font-family:tahoma,helvetica,arial;font-size:16px;line-height:21px;background-color:#FFF0D1;">页面中含有<!---->的注释去掉 from:<arel="nofollow">http://www.myexception.cn/ai/1462646.html好像没用。。。。始终不能生成logs和work下的文件<divclass="ref"> 引用来自“肖昌贵”的评论好像没用。。。。始终不能生成logs和work下的文件

爱吃鱼的程序员 2020-06-22 14:33:47 0 浏览量 回答数 0

回答

你的本地应用与容器分别运行在不同的虚拟机里,是不能直接互相访问对方的内部对象的。而且在容器内部,FacesContext实例是在Request Scope的(每个请求处理线程都有独立的FacesContext实例),你必须通过访问FacesServlet去创建出实例。 综上,你没办法在本地应用里直接访问容器里的FacesContext。但如果你知道需要获取什么信息,可以在容器上用某种方法(暴露WebService或RestFul API 或最简单的通过普通http响应)通过http协议返回你需要的数据。 例如,你可以写个页面 get-my-info.xhtml,里面只放一行代码 #{myInfoBean.returnInfo} 然后在你的myInfoBean的returnInfo方法中: public String returnInfo() { final String json = “。。。” //取到你需要的Managed Bean,把你需要的信息拼成JSON final FacesContext facesContext = FacesContext.getCurrentInstance(); final Object response = facesContext.getExternalContext().getResponse(); if (response instanceof HttpServletResponse) { final HttpServletResponse httpResponse = (HttpServletResponse) response; final PrintWriter writer = httpResponse.getWriter(); writer.append(json); httpResponse.setStatus(200); facesContext.responseComplete(); } return null; } 然后在你的本地应用里用HttpClient ( http://hc.apache.org/httpclient-3.x/ )之类的客户端包访问get-my-info.jsf,就能取到你在容器端拼出来的json信息。

长安归故里. 2020-01-31 14:05:04 0 浏览量 回答数 0

问题

Swarm API参考&nbsp;&nbsp;应用API调用方式&nbsp;&nbsp;调用方式

青蛙跳 2019-12-01 21:38:05 727 浏览量 回答数 0

回答

是的,你可以这么做。 您需要的材料: 网络服务器 Web服务器中存储的数据库 还有一点Android知识:) Webservices(json,Xml ... etc)随便您如何使用 1.首先在清单文件中设置Internet权限 2.创建一个类以从服务器发出HTTPRequest(我正在使用json parisng获取值) 例如: public class JSONfunctions { public static JSONObject getJSONfromURL(String url) { InputStream is = null; String result = ""; JSONObject jArray = null; // Download JSON data from URL try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } // Convert response to string try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { jArray = new JSONObject(result); } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return jArray; } } 3.在MainActivity“创建类的对象”中JsonFunctions,将url作为参数从您要获取数据的位置传递 例如: JSONObject jsonobject; jsonobject = JSONfunctions.getJSONfromURL("http://YOUR_DATABASE_URL"); 4.然后,最后读取jsontags并将值存储在arraylist中,如果需要,稍后在listview中显示它 如果您有任何问题,可以关注此博客,他提供了出色的android教程AndroidHive 由于上述答案我写了很长回来,现在HttpClient,HttpPost,HttpEntity已在阿比23.删除您可以使用下面的的build.gradle(应用级)的代码仍继续使用org.apache.http的项目。 android { useLibrary 'org.apache.http.legacy' signingConfigs {} buildTypes {} } 或者您可以使用HttpURLConnection如下所示从服务器获取响应 public String getJSON(String url, int timeout) { HttpURLConnection c = null; try { URL u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.connect(); int status = c.getResponseCode(); switch (status) { case 200: case 201: BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line+"\n"); } br.close(); return sb.toString(); } } catch (MalformedURLException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } finally { if (c != null) { try { c.disconnect(); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } } } return null; } 或您可以使用第三方库(如Volley)Retrofit来调用webservice api并获取响应,然后使用FasterXML-jackson,解析google-gson。来源:stack overflow

保持可爱mmm 2020-05-17 09:36:00 0 浏览量 回答数 0

问题

hive执行hadoop任务报错,求救!?报错

爱吃鱼的程序员 2020-06-22 18:11:13 0 浏览量 回答数 1

问题

springcloud eureka Read timed out?报错

爱吃鱼的程序员 2020-06-08 11:05:58 0 浏览量 回答数 0

回答

调用视频点播服务接口,是向视频点播服务端发送HTTP请求(可通过HTTP或HTTPS通道发送),并获取响应结果的过程。视频点播服务端接收到用户请求后,对请求进行身份验证和参数验证,验证成功后,根据请求的指定参数提交或完成相应操作,并把处理结果以HTTP响应的形式返回给调用者。 以下Java示例代码演示了如何添加公共参数和私有参数、如何用请求参数构造规范化请求字符串、如何构造StringToSign字符串,以及如何获得OpenAPI地址,最终以Get方式发送Http请求,获取相应的响应结果。如果您需要使用以下示例,请替换示例中的必选参数及私有参数。 添加jar包依赖 注意:使用httpclient get请求 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.1</version> </dependency> JAVA代码 import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import sun.misc.BASE64Encoder; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.security.SignatureException; import java.text.SimpleDateFormat; import java.util.*; import java.util.logging.Logger; /** * 视频点播OpenAPI调用示例 * 以GetVideoPlayAuth接口为例,其他接口请替换相应接口名称及私有参数 */ public class Main { //账号AccessKey信息请填写(必选) private static String access_key_id = ""; //账号AccessKey信息请填写(必选) private static String access_key_secret = ""; //STS临时授权方式访问时该参数为必选,使用主账号AccessKey和RAM子账号AccessKey不需要填写 private static String security_token = ""; //以下参数不需要修改 private final static String VOD_DOMAIN = "http://vod.cn-shanghai.aliyuncs.com"; private final static String ISO8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; private final static String HTTP_METHOD = "GET"; private final static String HMAC_SHA1_ALGORITHM = "HmacSHA1"; private final static String UTF_8 = "utf-8"; private final static Logger LOG = Logger.getLogger(Main.class.getName()); public static void main(String[] args) throws Exception { //生成私有参数,不同API需要修改 Map<String, String> privateParams = generatePrivateParamters(); //生成公共参数,不需要修改 Map<String, String> publicParams = generatePublicParamters(); //生成OpenAPI地址,不需要修改 String URL = generateOpenAPIURL(publicParams, privateParams); //发送HTTP GET 请求 httpGet(URL); } /** * 生成视频点播OpenAPI私有参数 * 不同API需要修改此方法中的参数 * @return */ private static Map<String, String> generatePrivateParamters() { // 接口私有参数列表, 不同API请替换相应参数 Map<String, String> privateParams = new HashMap<>(); // 视频ID privateParams.put("VideoId","5aed81b74ba84920be578cdfe004af4b"); // API名称 privateParams.put("Action", "GetVideoPlayAuth"); return privateParams; } /** * 生成视频点播OpenAPI公共参数 * 不需要修改 * @return */ private static Map<String, String> generatePublicParamters() { Map<String, String> publicParams = new HashMap<>(); publicParams.put("Format", "JSON"); publicParams.put("Version", "2017-03-21"); publicParams.put("AccessKeyId", access_key_id); publicParams.put("SignatureMethod", "HMAC-SHA1"); publicParams.put("Timestamp", generateTimestamp()); publicParams.put("SignatureVersion", "1.0"); publicParams.put("SignatureNonce", generateRandom()); if (security_token != null && security_token.length() > 0) { publicParams.put("SecurityToken", security_token); } return publicParams; } /** * 生成OpenAPI地址 * @param privateParams * @return * @throws Exception */ private static String generateOpenAPIURL(Map<String, String> publicParams, Map<String, String> privateParams) { return generateURL(VOD_DOMAIN, HTTP_METHOD, publicParams, privateParams); } /** * @param domain 请求地址 * @param httpMethod HTTP请求方式GET,POST等 * @param publicParams 公共参数 * @param privateParams 接口的私有参数 * @return 最后的url */ private static String generateURL(String domain, String httpMethod, Map<String, String> publicParams, Map<String, String> privateParams) { List<String> allEncodeParams = getAllParams(publicParams, privateParams); String cqsString = getCQS(allEncodeParams); out("CanonicalizedQueryString = " + cqsString); String stringToSign = httpMethod + "&" + percentEncode("/") + "&" + percentEncode(cqsString); out("StringtoSign = " + stringToSign); String signature = hmacSHA1Signature(access_key_secret, stringToSign); out("Signature = " + signature); return domain + "?" + cqsString + "&" + percentEncode("Signature") + "=" + percentEncode(signature); } private static List<String> getAllParams(Map<String, String> publicParams, Map<String, String> privateParams) { List<String> encodeParams = new ArrayList<String>(); if (publicParams != null) { for (String key : publicParams.keySet()) { String value = publicParams.get(key); //将参数和值都urlEncode一下。 String encodeKey = percentEncode(key); String encodeVal = percentEncode(value); encodeParams.add(encodeKey + "=" + encodeVal); } } if (privateParams != null) { for (String key : privateParams.keySet()) { String value = privateParams.get(key); //将参数和值都urlEncode一下。 String encodeKey = percentEncode(key); String encodeVal = percentEncode(value); encodeParams.add(encodeKey + "=" + encodeVal); } } return encodeParams; } /** * 参数urlEncode * * @param value * @return */ private static String percentEncode(String value) { try { String urlEncodeOrignStr = URLEncoder.encode(value, "UTF-8"); String plusReplaced = urlEncodeOrignStr.replace("+", "%20"); String starReplaced = plusReplaced.replace("*", "%2A"); String waveReplaced = starReplaced.replace("%7E", "~"); return waveReplaced; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return value; } /** * 获取CQS 的字符串 * * @param allParams * @return */ private static String getCQS(List<String> allParams) { ParamsComparator paramsComparator = new ParamsComparator(); Collections.sort(allParams, paramsComparator); String cqString = ""; for (int i = 0; i < allParams.size(); i++) { cqString += allParams.get(i); if (i != allParams.size() - 1) { cqString += "&"; } } return cqString; } private static class ParamsComparator implements Comparator<String> { @Override public int compare(String lhs, String rhs) { return lhs.compareTo(rhs); } } private static String hmacSHA1Signature(String accessKeySecret, String stringtoSign) { try { String key = accessKeySecret + "&"; try { SecretKeySpec signKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM); Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signKey); byte[] rawHmac = mac.doFinal(stringtoSign.getBytes()); //按照Base64 编码规则把上面的 HMAC 值编码成字符串,即得到签名值(Signature) return new String(new BASE64Encoder().encode(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } } catch (SignatureException e) { e.printStackTrace(); } return ""; } /** * 生成随机数 * * @return */ private static String generateRandom() { String signatureNonce = UUID.randomUUID().toString(); return signatureNonce; } /** * 生成当前UTC时间戳 * * @return */ public static String generateTimestamp() { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat df = new SimpleDateFormat(ISO8601_DATE_FORMAT); df.setTimeZone(new SimpleTimeZone(0, "GMT")); return df.format(date); } private static String httpGet(String url) throws Exception { CloseableHttpClient httpClient = null; try { httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(); httpGet.setURI(new URI(url)); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(3000) .setSocketTimeout(3000) .build(); httpGet.setConfig(requestConfig); HttpResponse result = httpClient.execute(httpGet); String str; try { /**读取服务器返回过来的json字符串数据**/ str = EntityUtils.toString(result.getEntity()); EntityUtils.consume(result.getEntity()); } catch (Exception e) { e.printStackTrace(); throw e; } out(str); // 这里可以解析视频云点播服务端的响应结果 return str; } catch (URISyntaxException e) { e.printStackTrace(); throw e; } catch (ClientProtocolException e) { e.printStackTrace(); throw e; } catch (IOException e) { e.printStackTrace(); throw e; } finally { try { if (httpClient != null) httpClient.close(); } catch (Exception e) { e.printStackTrace(); throw e; } } } private static void out(String newLine) { System.out.println(newLine); LOG.info(newLine); } } 最终得到URL: http://vod.cn-shanghai.aliyuncs.com?Signature=UI%2FwKfuvTtphzCKHwPhP0ErtLnc%3D&SignatureVersion=1.0&Action=GetVideoPlayAuth&Format=JSON&VideoId=68a4d2629a339db3207963ac073a88cd&SignatureNonce=578a50c1-280d-4a34-bffc-e06aa6b2df76&Version=2017-03-21&AccessKeyId=testId&SignatureMethod=HMAC-SHA1&Timestamp=2017-03-29T12%3A09%3A11Z 通过HTTP请求的方式向上述URL地址发送HTTP请求,得到响应结果,此处以JSON格式为例: { "RequestId": "25818875-5F78-4A13-BEF6-D7393642CA58", "VideoMeta": { "VideoId": "93ab850b4f6f44eab54b6e91d24d81d4", "Title": "阿里云VOD", "Duration": 135.6, "CoverURL": "https://image.example.com/sample.jpg", "Status": "Normal" }, "PlayAuth": "sstyYuew678999ew90000000xtt7TYUh" }

保持可爱mmm 2020-03-30 12:08:31 0 浏览量 回答数 0

问题

java调hbase 出错了? 400 报错

优选2 2020-06-09 11:11:41 0 浏览量 回答数 1

问题

java调hbase 出错了? 400 报错

爱吃鱼的程序员 2020-05-30 17:03:31 0 浏览量 回答数 1

回答

前台暴露你的appid?appikey?  jsonp貌似无解..... 后台获取的亲! 能使用后端获取吗?appidappkey都爆了。你可以ajax请求,后端获取数据后返回。不需要js跨域。 问题终于解决了。直接从后端获取: Stringurl="https://graph.qq.com/user/get_user_info"+"?"+"oauth_consumer_key="+getAppId()+"&access_token="+accessToken+"&openid="+openID;Strings=HttpClientUtil.sendGetRequest(url,"utf-8");QQUserInfoinfo=JSON.parseObject(s,QQUserInfo.class);StringuserImg=info.getFigureurl_qq_2(); /***发送HTTP_GET请求*@see该方法会自动关闭连接,释放资源*@paramrequestURL请求地址(含参数)*@paramdecodeCharset解码字符集,解析响应数据时用之,其为null时默认采用UTF-8解码*@return远程主机响应正文*/publicstaticStringsendGetRequest(StringreqURL,StringdecodeCharset){longresponseLength=0;//响应长度StringresponseContent=null;//响应内容HttpClienthttpClient=newDefaultHttpClient();//创建默认的httpClient实例HttpGethttpGet=newHttpGet(reqURL);//创建org.apache.http.client.methods.HttpGettry{SSLSocketFactory.getSocketFactory().setHostnameVerifier(newAllowAllHostnameVerifier());HttpResponseresponse=httpClient.execute(httpGet);//执行GET请求HttpEntityentity=response.getEntity();//获取响应实体if(null!=entity){responseLength=entity.getContentLength();responseContent=EntityUtils.toString(entity,decodeCharset==null?"UTF-8":decodeCharset);//EntityUtils.consume(entity);//Consumeresponsecontent}System.out.println("请求地址:"+httpGet.getURI());System.out.println("响应状态:"+response.getStatusLine());System.out.println("响应长度:"+responseLength);System.out.println("响应内容:"+responseContent);}catch(ClientProtocolExceptione){log.error("该异常通常是协议错误导致,比如构造HttpGet对象时传入的协议不对(将'http'写成'htp')或者服务器端返回的内容不符合HTTP协议要求等,堆栈信息如下",e);}catch(ParseExceptione){log.error(e.getMessage(),e);}catch(IOExceptione){log.error("该异常通常是网络原因引起的,如HTTP服务器未启动等,堆栈信息如下",e);}finally{httpClient.getConnectionManager().shutdown();//关闭连接,释放资源}returnresponseContent;} 感谢各位的参与!谢谢! 我最近也是遇到這个问题,折磨了一天最终还是不能直接跨域,基本上的api接口都没有添加jsonp,返回的js对象,所以就不能用了。 我还想了不知道可不可以用js获取到当前页面访问过的资源,因为上面的那种ajax后有那些作为错误的js文件存在,然后把这些文件读取在作为需要的数据?可行么?如果可以的话,都改成get请求,就不存在post跨域问题了,我是说如果可以。否则的话,就用某种语言的http模块来做吧。

爱吃鱼的程序员 2020-06-14 22:17:52 0 浏览量 回答数 0

回答

本文列举了Web应用托管服务的API的公共请求头和公共返回头信息。 公共请求头部 公共请求参数是指每个接口都需要使用到的请求参数。 参数名称 示例 是否必选 说明 Authorization acs : 是 用于验证请求合法性的认证信息,采用 AccessKeyId:Signature 的形式。 Content-Length 0 是 RFC 2616 中定义的 HTTP 请求内容长度。 Content-Type application/json 是 RFC 2616 中定义的 HTTP 请求内容类型。 Content-MD5 0e30656xxxxxxxxx0bc6f70bbdfe 是 HTTP 协议消息体的 128-bit MD5 散列值转换成 BASE64 编码的结果。为了防止所有请求被篡改,建议所有请求都附加该信息。 Date Fri, 16 Aug 2019 11:18:47 GMT 是 请求的构造时间,目前只支持 GMT 格式。如果与 MNS 的服务器时间前后差异超过 15 分钟将返回本次请求非法。 Host webplus.cn-hangzhou.aliyuncs.com 是 请求的服务地址,例如:webplus.cn-hangzhou.aliyuncs.com。 Accept application/json 是 客户端需要的返回值类型,支持 application/json 和 application/xml。 x-acs-version 1.0 是 API 版本号。目前版本号为 2019-03-20。 x-acs-region-id cn-hangzhou 是 地域ID。 x-acs-signature-nonce f63659d4-10ac-483b-99da-ea8fde61eae3 是 唯一随机数,用于防止网络重放攻击。您在不同请求间要使用不同的随机数值。 x-acs-signature-method HMAC-SHA1 是 用户签名方式,目前只支持 HMAC-SHA1。 示例 GET /pop/v1/wam/appEnv HTTP/1.1 Host: webplus.cn-hangzhou.aliyuncs.com Accept: application/json UserAgent : Apache-HttpClient/4.5.7 (Java/1.8.0_152) x-acs-signature-nonce: f63659d4-10ac-483b-99da-ea8fde61eae3 Authorization: acs : x-acs-signature-version: 1.0 Date: Fri, 16 Aug 2019 11:18:47 GMT x-acs-signature-method: HMAC-SHA1 Content-Type: application/json;charset=utf-8 X-Acs-Region-Id: cn-hangzhou Content-Length: 0 公共返回头部 每次接口调用请求,无论成功与否,系统都会返回一个唯一识别码RequestId。调用API服务后返回数据采用统一格式。返回的HTTP状态码为 2xx,代表调用成功;返回的HTTP状态码为 4xx 或 5xx,代表调用失败。 XML 示例: <接口名称+response> | | 4C467B38-3910-447D-87BC-AC049166F216 | JSON 示例: { "RequestId": "4C467B38-3910-447D-87BC-AC049166F216" /* 返回结果数据 */ }

1934890530796658 2020-03-23 14:43:41 0 浏览量 回答数 0

问题

无法初始化主类的原因?

montos 2020-03-22 08:37:27 1 浏览量 回答数 1

问题

MANIFEST.MF个例中配置详解:报错

kun坤 2020-06-14 07:12:56 0 浏览量 回答数 1

问题

MANIFEST.MF个例中配置详解 - maven报错

montos 2020-06-02 21:31:35 0 浏览量 回答数 1
阿里云大学 云服务器ECS com域名 网站域名whois查询 开发者平台 小程序定制 小程序开发 国内短信套餐包 开发者技术与产品 云数据库 图像识别 开发者问答 阿里云建站 阿里云备案 云市场 万网 阿里云帮助文档 免费套餐 开发者工具 企业信息查询 小程序开发制作 视频内容分析 企业网站制作 视频集锦 代理记账服务 企业建站模板