GVKun编程网logo

如何使用 POST 使用 NameValuePair 将参数添加到 HttpURLConnection(post请求可以把参数放在url里吗)

15

本文将分享如何使用POST使用NameValuePair将参数添加到HttpURLConnection的详细内容,并且还将对post请求可以把参数放在url里吗进行详尽解释,此外,我们还将为大家带来关

本文将分享如何使用 POST 使用 NameValuePair 将参数添加到 HttpURLConnection的详细内容,并且还将对post请求可以把参数放在url里吗进行详尽解释,此外,我们还将为大家带来关于Android HTTPUrlConnection POST、android – 如何使用NameValuePair使用POST向HttpURLConnection添加参数、Http - Do a POST with HttpURLConnection、HttpUrlConnection Get 和Post请求的相关知识,希望对你有所帮助。

本文目录一览:

如何使用 POST 使用 NameValuePair 将参数添加到 HttpURLConnection(post请求可以把参数放在url里吗)

如何使用 POST 使用 NameValuePair 将参数添加到 HttpURLConnection(post请求可以把参数放在url里吗)

我正在尝试使用POST HttpURLConnection我需要以这种方式使用它,不能使用HttpPost)并且我想向该连接添加参数,例如

post.setEntity(new UrlEncodedFormEntity(nvp));

在哪里

nvp = new ArrayList<NameValuePair>();

存储了一些数据。我找不到如何将其添加ArrayList到我的HttpURLConnection方法,这里是:

HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);

尴尬的 https 和 http 组合的原因是不需要 验证 证书。不过,这不是问题,它可以很好地发布服务器。但我需要它来发表论据。

有任何想法吗?


重复免责声明:

早在 2012 年,我不知道参数是如何插入到 HTTP POST
请求中的。我一直在坚持,NameValuePair因为它在教程中。

Android HTTPUrlConnection POST

Android HTTPUrlConnection POST

我正在使用HttpURLConnection通过POST将数据发送到服务器.我设置头,然后获取输出流并写入5个字节的数据(“ M = 005”),然后关闭输出流.

在服务器上,我收到了所有标头,正确的内容长度,但是随后得到的长度为零,并且服务器挂在readLine上.

似乎发生的事情是客户端关闭实际上从未发生,因此不会写入整个数据,因此服务器永远不会获得它.

我已经阅读了许多示例,并尝试了各种更改,以查看我是否可以以任何方式实现此目标,而效果均不理想.例如,关闭保持活动状态,然后在数据末尾强制执行CRLF(这会迫使我的数据在服务器端发出,但连接仍无法关闭.(仅用于测试),尝试使用打印写程序.

由于很多示例都在执行我的操作,因此我认为这很简单,但是我看不到它.任何帮助,将不胜感激.

    StringBuilder postDataBuilder.append("M=").append(URLEncoder.encode("005", UTF8));
    byte[] postData = null;
    postData = postDataBuilder.toString().getBytes();


    url = new URL("http://" + serverAddress + ":" + String.valueOf(serverPort));
    conn = (HttpURLConnection) url.openConnection();

    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
    conn.setUseCaches(false);

    OutputStream out = conn.getoutputStream();
    out.write(postData);
    out.close();

    int responseCode = conn.getResponseCode();

    // After executing the above line the server starts to successfully readLines
    // until it gets to the post data when the server hangs.  If I restart the
    // client side then the data finally gets through but the connection on the
    // server side never ends. 

解决方法:

哎呀我们服务器端的错误是执行readLine而不是字符读取.由于没有CRLF,它将挂起.

android – 如何使用NameValuePair使用POST向HttpURLConnection添加参数

android – 如何使用NameValuePair使用POST向HttpURLConnection添加参数

我正在尝试使用HttpURLConnection进行POST(我需要以这种方式使用它,不能使用HttpPost)并且我想将参数添加到该连接中,例如

post.setEntity(new UrlEncodedFormEntity(nvp));

哪里

nvp = new ArrayList<NameValuePair>();

有一些数据存储在.我找不到如何将这个ArrayList添加到我的HttpURLConnection的方法,这是在这里:

HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);

这种尴尬的https和http组合的原因是不需要验证证书.但这不是问题,它可以很好地发布服务器.但是我需要用论据发帖.

有任何想法吗?

重复免责声明:

回到2012年,我不知道如何将参数插入到HTTP POST请求中.我在NameValuePair上,因为它是在教程中.这个问题可能看似重复,但是,我的2012年自己阅读了other问题并且它没有使用NameValuePair.事实上,它并没有解决我的问题.

解决方法:

您可以获取连接的输出流并将参数查询字符串写入其中.

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getoutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

Http - Do a POST with HttpURLConnection

Http - Do a POST with HttpURLConnection

In a GET request, the parameters are sent as part of the URL.

In a POST request, the parameters are sent as a body of the request, after the headers.

To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

This code should get you started:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;

public class Test {
	public static void main(String[] args) throws Exception {
		URL url = new URL("http://example.net/new-message.php");
		Map<String, Object> params = new LinkedHashMap<>();
		params.put("name", "Freddie the Fish");
		params.put("email", "fishie@seamail.example.com");
		params.put("reply_to_thread", 10394);
		params.put("message",
				"Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He''s so shellfish.");

		StringBuilder postData = new StringBuilder();
		for (Map.Entry<String, Object> param : params.entrySet()) {
			if (postData.length() != 0)
				postData.append(''&'');
			postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
			postData.append(''='');
			postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
		}
		byte[] postDataBytes = postData.toString().getBytes("UTF-8");

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
		conn.setDoOutput(true);
		conn.getOutputStream().write(postDataBytes);

		Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

		for (int c; (c = in.read()) >= 0;)
			System.out.print((char) c);
	}
}

If you want the result as a String instead of directly printed out do:

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0;)
            sb.append((char)c);
        String response = sb.toString();

 

 

参考:

http://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily

http://hgoebl.github.io/DavidWebb/

HttpUrlConnection Get 和Post请求

HttpUrlConnection Get 和Post请求

package com.example.demo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.text.TextUtils;

public class UrlConnManager {

	/**
	 * Get 请求
	 * @param path
	 * @return
	 */
	public static String getDataByGet(String path){
		try {
			URL url = new URL(path.trim());
			//打开连接
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			//设置链接超时时间
			urlConnection.setConnectTimeout(15000);
			//设置读取超时时间
			urlConnection.setReadTimeout(15000);
			if(200 == urlConnection.getResponseCode()){
				//得到输入流
				InputStream is =urlConnection.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int len = 0;
				while(-1 != (len = is.read(buffer))){
					baos.write(buffer,0,len);
					baos.flush();
				}
				return baos.toString("utf-8");
			}
		}  catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

    /**
     * Post 请求  (参数以&连接)
     * @param url
     */
	public static String getDataByPost(String url) {
		String result = null;
		InputStream mInputStream = null;
		HttpURLConnection mHttpURLConnection = UrlConnManager.getHttpURLConnection(url);
		try {
			List<NameValuePair> postParams = new ArrayList<>();
			//要传递的参数
			postParams.add(new BasicNameValuePair("username", "moon"));
			postParams.add(new BasicNameValuePair("password", "123"));
			UrlConnManager.postParams(mHttpURLConnection.getOutputStream(), postParams);
			mHttpURLConnection.connect();
			mInputStream = mHttpURLConnection.getInputStream();
			int code = mHttpURLConnection.getResponseCode();
			result = converStreamToString(mInputStream);
            
			mInputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
     * Post 请求  (参数为json字符串)
     * @param url
     */
	public static String getDataByPost(String url,String json) {
		String result = null;
	        try {  
	        	URL mUrl = new URL(url);  
	            HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();  
	            conn.setRequestMethod("POST");// 提交模式  
	            //是否允许输入输出  
	            conn.setDoInput(true);  
	            conn.setDoOutput(true);  
	            //设置请求头里面的数据,以下设置用于解决http请求code415的问题  
	            conn.setRequestProperty("Content-Type","application/json");  //设置json格式
	            //链接地址  
	            conn.connect();  
	            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());  
	            //发送参数  
	            writer.write(json);  
	            //清理当前编辑器的左右缓冲区,并使缓冲区数据写入基础流  
	            writer.flush();  
	            BufferedReader reader = new BufferedReader(new InputStreamReader(    
	                    conn.getInputStream()));    
	            result =reader.readLine();//读取请求结果  	           
	            reader.close();  
	           
		} catch (IOException e) {
			e.printStackTrace();
		}
	    return result;
	}

	public static void postParams(OutputStream output,List<NameValuePair>paramsList) throws IOException{
		StringBuilder mStringBuilder=new StringBuilder();
		for (NameValuePair pair:paramsList){
			if(!TextUtils.isEmpty(mStringBuilder)){
				mStringBuilder.append("&");
			}
			mStringBuilder.append(URLEncoder.encode(pair.getName(),"UTF-8"));
			mStringBuilder.append("=");
			mStringBuilder.append(URLEncoder.encode(pair.getValue(),"UTF-8"));
		}
		BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(output,"UTF-8"));
		writer.write(mStringBuilder.toString());
		writer.flush();
		writer.close();
	}

	

	public static HttpURLConnection getHttpURLConnection(String url){
		HttpURLConnection mHttpURLConnection=null;
		try {
			URL mUrl=new URL(url);
			mHttpURLConnection=(HttpURLConnection)mUrl.openConnection();
			//设置链接超时时间
			mHttpURLConnection.setConnectTimeout(15000);
			//设置读取超时时间
			mHttpURLConnection.setReadTimeout(15000);
			//设置请求参数
			mHttpURLConnection.setRequestMethod("POST");
			//添加Header
			mHttpURLConnection.setRequestProperty("Connection","Keep-Alive");
			//接收输入流
			mHttpURLConnection.setDoInput(true);
			//传递参数时需要开启
			mHttpURLConnection.setDoOutput(true);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mHttpURLConnection ;
	}

	private static String converStreamToString(InputStream is) {   
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));   
		StringBuilder sb = new StringBuilder();   
		String line = null; 
		try {   
			while ((line = reader.readLine()) != null) {
				sb.append(line + "/n");   
			}   

		} catch (IOException e) {  
			e.printStackTrace();   
		} finally {   
			try {   
				is.close();   

			} catch (IOException e) {  
				e.printStackTrace();  
			}   
		}      
		return sb.toString();
	}   

}

我们今天的关于如何使用 POST 使用 NameValuePair 将参数添加到 HttpURLConnectionpost请求可以把参数放在url里吗的分享已经告一段落,感谢您的关注,如果您想了解更多关于Android HTTPUrlConnection POST、android – 如何使用NameValuePair使用POST向HttpURLConnection添加参数、Http - Do a POST with HttpURLConnection、HttpUrlConnection Get 和Post请求的相关信息,请在本站查询。

本文标签: