Java POST数据未通过HttpURLConnection发送
我正在尝试通过HttpURLConnection发送POST请求,下面是代码Java POST数据未通过HttpURLConnection发送,java,android,post,Java,Android,Post,我正在尝试通过HttpURLConnection发送POST请求,下面是代码 public class BackgroundTask extends AsyncTask<String, Void, Void> { Context context; Activity activity; StringBuffer str = null; int responseCode; String responseMessage; public Ba
public class BackgroundTask extends AsyncTask<String, Void, Void> {
Context context;
Activity activity;
StringBuffer str = null;
int responseCode;
String responseMessage;
public BackgroundTask(Context context) {
this.context = context;
this.activity = (Activity) context;
}
@Override
protected Void doInBackground(String... params) {
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader reader = null;
BufferedWriter writer = null;
String method = params[1];
if(method.equals("post")) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
outputStream = connection.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
writer.write(data);
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
str = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if(method.equals("get")) {
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(Void aVoid) {
TextView txt = (TextView) activity.findViewById(R.id.txt);
if(str != null)
txt.setText(str.toString());
Toast.makeText(activity, responseMessage, Toast.LENGTH_LONG).show();
}
}
当我从html文件发送post请求时,它工作正常,但当我从应用程序发送它时,它会说id未定义,这意味着post数据未发送
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BackgroundTask myTask = new BackgroundTask(MainActivity.this);
myTask.execute(link, "post", "id", "5");
}
});
这就是我在主活动中实例化asynctask对象的方式
更新:当我发送未编码的字符串时,它工作正常!
writer.write(“id=5”);//很好用!
我在代码中使用的URLEncoder有什么问题?当我需要与服务器通信时,我使用此 服务器类
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);
公共静态字符串sendPostRequest(字符串请求URL,
HashMap postDataParams){
网址;
字符串响应=”;
试一试{
url=新url(请求url);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
连接设置读取超时(15000);
连接设置连接超时(15000);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
OutputStream os=conn.getOutputStream();
BufferedWriter=新的BufferedWriter(
新的OutputStreamWriter(操作系统,“UTF-8”);
write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if(responseCode==HttpsURLConnection.HTTP\u确定){
BufferedReader br=新的BufferedReader(新的InputStreamReader(conn.getInputStream());
response=br.readLine();
}否则{
response=“注册错误”;
}
}捕获(例外e){
e、 printStackTrace();
}
返回响应;
}
私有静态字符串getPostDataString(HashMap参数)引发UnsupportedEncodingException{
StringBuilder结果=新建StringBuilder();
布尔值优先=真;
对于(Map.Entry:params.entrySet()){
如果(第一)
第一个=假;
其他的
结果。追加(&);
append(URLEncoder.encode(entry.getKey(),“UTF-8”);
结果。追加(“=”);
append(URLEncoder.encode(entry.getValue(),“UTF-8”);
}
返回result.toString();
}
OtherClass
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);
//在异步任务中运行此任务
HashMap数据=新的HashMap();
数据输入(“id”,id);
字符串serverresponse=Server.sendPostRequest(URL,数据);
当我需要与服务器通信时,我使用此
服务器类
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);
公共静态字符串sendPostRequest(字符串请求URL,
HashMap postDataParams){
网址;
字符串响应=”;
试一试{
url=新url(请求url);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
连接设置读取超时(15000);
连接设置连接超时(15000);
conn.setRequestMethod(“POST”);
conn.setDoInput(真);
连接设置输出(真);
OutputStream os=conn.getOutputStream();
BufferedWriter=新的BufferedWriter(
新的OutputStreamWriter(操作系统,“UTF-8”);
write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if(responseCode==HttpsURLConnection.HTTP\u确定){
BufferedReader br=新的BufferedReader(新的InputStreamReader(conn.getInputStream());
response=br.readLine();
}否则{
response=“注册错误”;
}
}捕获(例外e){
e、 printStackTrace();
}
返回响应;
}
私有静态字符串getPostDataString(HashMap参数)引发UnsupportedEncodingException{
StringBuilder结果=新建StringBuilder();
布尔值优先=真;
对于(Map.Entry:params.entrySet()){
如果(第一)
第一个=假;
其他的
结果。追加(&);
append(URLEncoder.encode(entry.getKey(),“UTF-8”);
结果。追加(“=”);
append(URLEncoder.encode(entry.getValue(),“UTF-8”);
}
返回result.toString();
}
OtherClass
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);
//在异步任务中运行此任务
HashMap数据=新的HashMap();
数据输入(“id”,id);
字符串serverresponse=Server.sendPostRequest(URL,数据);
我相信您在这方面遇到了问题:
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
您正在对=
以及参数进行url编码,这就是服务器无法识别表单字段的原因。尝试仅对参数进行编码:
String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
原因是URL编码用于在值(或键)中传递特殊字符,如
=
。基本上,在解码之前,服务器将使用&
和=
拆分和解析键值对。当您对=
字符进行url编码时,服务器在拆分和解析阶段根本无法识别它。我相信您在这方面有问题:
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
您正在对=
以及参数进行url编码,这就是服务器无法识别表单字段的原因。尝试仅对参数进行编码:
String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
原因是URL编码用于在值(或键)中传递特殊字符,如
=
。基本上,在解码之前,服务器将使用&
和=
拆分和解析键值对。当您对=
字符进行url编码时,服务器在拆分和解析阶段根本无法识别它。writer.write(“id=5”);//很好用!URLEncoder有一个问题,我不知道为什么写入程序。写入(“id=5”);//很好用!URLEncoder有一个问题,我不知道为什么可能不需要对参数进行编码name@ScaryWombat最好是安全的。可能不需要对参数进行编码name@ScaryWombat最好是安全的。