本文将带您了解关于使用http.Client和http.Transport设置请求标头的新内容,同时我们还将为您解释httpclient设置请求头的相关知识,另外,我们还将为您提供关于<经验&g
本文将带您了解关于使用http.Client和http.Transport设置请求标头的新内容,同时我们还将为您解释httpclient 设置请求头的相关知识,另外,我们还将为您提供关于<经验>使用HttpClient做Http请求、Android JSON HttpClient使用HttpResponse将数据发送到PHP服务器、android – 使用HttpClient的HTTP请求太慢了?、android使用HttpGet和HttpPost访问HTTP资源的实用信息。
本文目录一览:- 使用http.Client和http.Transport设置请求标头(httpclient 设置请求头)
- <经验>使用HttpClient做Http请求
- Android JSON HttpClient使用HttpResponse将数据发送到PHP服务器
- android – 使用HttpClient的HTTP请求太慢了?
- android使用HttpGet和HttpPost访问HTTP资源
使用http.Client和http.Transport设置请求标头(httpclient 设置请求头)
我有多个IP可以上网。我正在请求选择界面。在这种情况下,我应该如何设置标题?
tcpAddr := &net.TCPAddr{ IP: addrs[3].(*net.IPNet).IP, // Choosing ip address number 3}d := net.Dialer{LocalAddr: tcpAddr}conn, err2 := d.Dial("tcp", "www.whatismyip.com:80")if err2 != nil { log.Fatal(err2)}defer conn.Close()transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{LocalAddr: tcpAddr}).Dial, TLSHandshakeTimeout: 10 * time.Second,}client := &http.Client{ Transport: transport,}response, err := client.Get("https://www.whatismyip.com/")
通常,头是以这种方式设置的:
req.Header.Set("name", "value")
但是无法弄清楚如何将它们设置为我的代码。
我想它们必须放在http.Transport
或中的某个位置http.Client
。但是到底如何呢?
我的完整代码:
package mainimport ( "bytes" "fmt" "github.com/PuerkitoBio/goquery" "io/ioutil" "log" "net" "net/http" "os" "time")func main() { ief, err := net.InterfaceByName("eth0") if err != nil { log.Fatal(err) } addrs, err := ief.Addrs() if err != nil { log.Fatal(err) } tcpAddr := &net.TCPAddr{ IP: addrs[3].(*net.IPNet).IP, // Choosing ip address number 3 } d := net.Dialer{LocalAddr: tcpAddr} conn, err2 := d.Dial("tcp", "www.whatismyip.com:80") if err2 != nil { log.Fatal(err2) } defer conn.Close() transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{LocalAddr: tcpAddr}).Dial, TLSHandshakeTimeout: 10 * time.Second, } client := &http.Client{ Transport: transport, } response, err := client.Get("https://www.whatismyip.com/") if err != nil { fmt.Printf("%s", err) os.Exit(1) } else { defer response.Body.Close() contents, err := ioutil.ReadAll(response.Body) if err != nil { fmt.Printf("%s", err) os.Exit(1) } var contentsStr = string(contents) fmt.Printf("%s\n", contentsStr) var doc = DocByHtmlString(contentsStr) doc.Find("div").Each(func(i int, s *goquery.Selection) { attr, exists := s.Attr("class") if exists { if attr == "ip" { fmt.Println(s.Text()) } } }) }}func DocByHtmlString(html string) *goquery.Document { doc, err := goquery.NewDocumentFromReader(bytes.NewBufferString(html)) if err != nil { panic(err) } return doc}
答案1
小编典典创建一个请求:
req, err := http.NewRequest("GET", "https://www.whatismyip.com/", nil) if err != nil { // handle error }
设置标题:
req.Header.Set("name", "value")
使用client
问题中配置的方式运行请求:
resp, err := client.Do(req) if err != nil { // handle error }
按照问题所示处理响应。
<经验>使用HttpClient做Http请求
package cn.com.wind.utils; import cn.com.wind.exception.TranspondException; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.RequestEntity; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; import org.apache.http.httpentity; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; 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 java.io.*; import java.nio.charset.StandardCharsets; /** * @Author qymeng * @Date 2021/10/25 * @Description 接口转发的工具类 */ @Slf4j public class TranspondUtils { /** * POST请求 * * @param json 请求的json体 * @param url 请求的URL地址 */ public static String doPost(String json, String url) { HttpClient httpClient = new HttpClient(); // 设置http连接主机服务超时时间 httpClient.gethttpconnectionManager().getParams().setConnectionTimeout(35000); PostMethod postMethod = new PostMethod(url); // 设置post请求超时 postMethod.getParams().setParameter(HttpMethodParams.so_TIMEOUT, 60000); // 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true)); String result = null; try { RequestEntity entity = new StringRequestEntity(json, "application/json", "UTF-8"); //请求头信息 postMethod.setRequestHeader("Content-Type", "application/json"); postMethod.setRequestEntity(entity); httpClient.executeMethod(postMethod); if (postMethod.getStatusCode() == HttpStatus.SC_OK) { // 获取响应输入流 InputStream inStream = postMethod.getResponseBodyAsstream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, StandardCharsets.UTF_8)); StringBuilder strber = new StringBuilder(); String line; while ((line = reader.readLine()) != null) strber.append(line).append("\n"); inStream.close(); result = strber.toString(); } else { throw new TranspondException("请求服务端失败,状态码不为200"); } } catch (IOException e) { throw new TranspondException("请求服务端失败,地址为:" + url); } catch (IllegalStateException e) { throw new TranspondException("URL地址不正确,该地址为:" + url); } catch (Exception e) { throw new TranspondException("其他异常"); } return result; } public static String doPost(JSONObject json, String url) { String s = JSON.toJSONString(json); return doPost(s, url); } public static String doPost(Object json, String url) { String s = JSON.toJSONString(json); return doPost(s, url); } /** * GET请求 * * @param url 请求的URL地址 */ public static String doGet(String url) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String result = ""; try { // 通过址默认配置创建一个httpClient实例 httpClient = HttpClients.createDefault(); // 创建httpGet远程连接实例 HttpGet httpGet = new HttpGet(url); // 设置配置请求参数 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间 .setConnectionRequestTimeout(35000)// 请求超时时间 .setSocketTimeout(60000)// 数据读取超时时间 .build(); // 为httpGet实例设置配置 httpGet.setConfig(requestConfig); // 执行get请求得到返回对象 response = httpClient.execute(httpGet); // 通过返回对象获取返回数据 httpentity entity = response.getEntity(); // 通过EntityUtils中的toString方法将结果转换为字符串 result = EntityUtils.toString(entity); // log.info("请求服务器成功"); } catch (IOException e) { throw new TranspondException("GET请求异常, URL为:" + url); } finally { // 关闭资源 if (null != response) { try { response.close(); } catch (IOException e) { throw new TranspondException("关闭CloseableHttpResponse时出现异常, URL为:" + url); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { throw new TranspondException("关闭CloseableHttpClient时出现异常, URL为:" + url); } } } return result; } public static JSONObject doGetJson(String url) { return JSONObject.parSEObject(doGet(url)); } }
总结
以上是小编为你收集整理的<经验>使用HttpClient做Http请求全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
原文地址:https://www.cnblogs.com/aeimio/p/16178471.html
Android JSON HttpClient使用HttpResponse将数据发送到PHP服务器
我目前正在尝试从Android应用程序向php服务器发送数据(两者均由我控制)。
应用程序中的表单上收集了很多数据,这些数据已写入数据库。所有这一切。
在我的主代码中,首先我创建一个JSONObject(在此示例中,我已在此处将其裁剪):
JSONObject j = new JSONObject();j.put("engineer", "me");j.put("date", "today");j.put("fuel", "full");j.put("car", "mine");j.put("distance", "miles");
接下来,我将对象传递给发送对象,并接收响应:
String url = "http://www.server.com/thisfile.php";HttpResponse re = HTTPPoster.doPost(url, j);String temp = EntityUtils.toString(re.getEntity());if (temp.compareTo("SUCCESS")==0){ Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();}
HTTPPoster类:
public static HttpResponse doPost(String url, JSONObject c) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost request = new HttpPost(url); HttpEntity entity; StringEntity s = new StringEntity(c.toString()); s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); entity = s; request.setEntity(entity); HttpResponse response; response = httpclient.execute(request); return response;}
这将获得响应,但是服务器返回403-禁止响应。
我试过稍微更改doPost函数(实际上好一点,正如我说的,我有很多东西要发送,基本上是3个具有不同数据的相同表单-
所以我创建了3个JSONObject,每个表单项一个-条目来自数据库而不是我使用的静态示例)。
首先,我将通话更改了一点:
String url = "http://www.myserver.com/ServiceMatalan.php";Map<String, String> kvPairs = new HashMap<String, String>();kvPairs.put("vehicle", j.toString());// Normally I would pass two more JSONObjects.....HttpResponse re = HTTPPoster.doPost(url, kvPairs);String temp = EntityUtils.toString(re.getEntity());if (temp.compareTo("SUCCESS")==0){ Toast.makeText(this, "Sending complete!", Toast.LENGTH_LONG).show();}
好的,对doPost函数的更改如下:
public static HttpResponse doPost(String url, Map<String, String> kvPairs) throws ClientProtocolException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); if (kvPairs != null && kvPairs.isEmpty() == false) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size()); String k, v; Iterator<String> itKeys = kvPairs.keySet().iterator(); while (itKeys.hasNext()) { k = itKeys.next(); v = kvPairs.get(k); nameValuePairs.add(new BasicNameValuePair(k, v)); } httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } HttpResponse response; response = httpclient.execute(httppost); return response;}
好的,这将返回响应200
int statusCode = re.getStatusLine().getStatusCode();
但是,服务器上接收到的数据无法解析为JSON字符串。我认为它的格式有误(这是我第一次使用JSON):
如果在php文件中,我在$ _POST [‘vehicle’]上执行回显,则得到以下信息:
{\"date\":\"today\",\"engineer\":\"me\"}
谁能告诉我我哪里出问题了,或者是否有更好的方法来实现我的目标?希望以上是有道理的!
答案1
小编典典经过大量阅读和搜索之后,我发现问题出在哪里,我相信在服务器上启用了magic_quotes_gpc。
因此,使用:
json_decode(stripslashes($_POST[''vehicle'']));
在上面的示例中,删除了斜杠,并允许对JSON进行正确解码。
仍然不确定为什么发送StringEntity会导致403错误?
android – 使用HttpClient的HTTP请求太慢了?
代码是这样的
HttpPost httppost; DefaultHttpClient httpclient; httppost = new HttpPost("http://IP/script.PHP"); HttpParams param = new BasicHttpParams(); param.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1); // httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false); HttpProtocolParams.setContentCharset(param,"UTF-8"); httpclient = new DefaultHttpClient(param); ResponseHandler <String> res=new BasicResponseHandler(); List<NameValuePair> nameValuePairs; nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("id","1")); nameValuePairs.add(new BasicNameValuePair("api","1")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); Log.v("1",System.currentTimeMillis()+"");// Log to kNow the time diff String result= httpclient.execute(httppost,res); Log.v("2",System.currentTimeMillis()+""); // Log to kNow the time diff
这段代码浪费了大约2.5秒(在3G或WiFi上)发送帖子并从服务器获得“ok”字符串,即使有好的wifi这次只下来2.2 / 2.0秒
我在我的计算机上运行了一个简单的Ajax发送邮件脚本,通过同一部手机和3G连接到互联网,需要大约.300ms才能做同样的事情¿相同的连接,相同的动作,2秒的差异?
/// *** UPDATE
我在我的计算机上再次尝试了我的jquery脚本(带有移动3G / HDSPA连接)
平均时间响应约为250毫秒,但总是第一次请求高达1.7秒,我试图发送间隔为30秒的帖子,我得到平均1.5秒的时间,然后我试图发送间隔为2秒的帖子,第一次是1.41s,接近252ms
在这里,你们可以查看图表:http://i46.tinypic.com/27zjl8n.jpg
这种与电缆连接(标准家庭DSL)相同的测试始终提供约170ms间隔的固定时间响应(这里没有可靠的参数,但恕我直言,可能第一次尝试略高一点)
因此,在第一次尝试中有一些(或错误的)严重影响移动连接的东西,任何想法的人?
解决方法
HttpClient httpclient = new DefaultHttpClient(); HttpParams httpParameters = httpclient.getParams(); httpconnectionParams.setConnectionTimeout(httpParameters,CONNECTION_TIMEOUT); httpconnectionParams.setSoTimeout(httpParameters,WAIT_RESPONSE_TIMEOUT); httpconnectionParams.setTcpNoDelay(httpParameters,true);
这是关于setTcpNoDelay的javadoc:
public static void setTcpNoDelay(HttpParams params,boolean value)
Since: API Level 1
Determines whether Nagle’s algorithm is to be used. The Nagle’s
algorithm tries to conserve bandwidth by minimizing the number of
segments that are sent. When applications wish to decrease network
latency and increase performance,they can disable Nagle’s algorithm
(that is enable TCP_NODELAY). Data will be sent earlier,at the cost
of an increase in bandwidth consumption.Parameters
value true if the Nagle’s algorithm is to NOT be used (that is enable TCP_NODELAY),false otherwise.
android使用HttpGet和HttpPost访问HTTP资源
需求:用户登录(name:用户名,pwd:密码)(一)HttpGet :doGet()方法
//doGet():将参数的键值对附加在url后面来传递
public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{
//服务器 :服务器项目 :servlet名称
String path="http://192.168.5.21:8080/test/test";
String uri=path+"?name="+name+"&pwd="+pwd;
//name:服务器端的用户名,pwd:服务器端的密码
//注意字符串连接时不能带空格
String result="";
HttpGet httpGet=new HttpGet(uri);
HttpResponse response=new DefaultHttpClient().execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result=EntityUtils.toString(entity, HTTP.UTF_8);
}
return result;
}
(二)HttpPost :doPost()方法
//doPost():将参数打包到http报头中传递
public String getReultForHttpPost(String name,String pwd) throws ClientProtocolException, IOException{
//服务器 :服务器项目 :servlet名称
String path="http://192.168.5.21:8080/test/test";
HttpPost httpPost=new HttpPost(path);
List<NameValuePair>list=new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", name));
list.add(new BasicNameValuePair("pwd", pwd));
httpPost.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));
String result="";
HttpResponse response=new DefaultHttpClient().execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result=EntityUtils.toString(entity, HTTP.UTF_8);
}
return result;
}
今天关于使用http.Client和http.Transport设置请求标头和httpclient 设置请求头的讲解已经结束,谢谢您的阅读,如果想了解更多关于<经验>使用HttpClient做Http请求、Android JSON HttpClient使用HttpResponse将数据发送到PHP服务器、android – 使用HttpClient的HTTP请求太慢了?、android使用HttpGet和HttpPost访问HTTP资源的相关知识,请在本站搜索。
本文标签: