HttpURLConnection在Java中工作,但在android中不工作
我们一直在尝试向android应用程序中的node.js服务器发送POST请求。因为旧的apache依赖项已被弃用(我似乎无法访问它们——我已经尝试过了),所以我们一直在使用HttpURLConnection类。我们已经用java编写了一个类,它只作为一个独立的类(Request.java)工作,但是当在android程序中输入时,它每次都会抛出一个错误,当试图获取错误消息时,它只返回null Request.javaHttpURLConnection在Java中工作,但在android中不工作,java,android,http,Java,Android,Http,我们一直在尝试向android应用程序中的node.js服务器发送POST请求。因为旧的apache依赖项已被弃用(我似乎无法访问它们——我已经尝试过了),所以我们一直在使用HttpURLConnection类。我们已经用java编写了一个类,它只作为一个独立的类(Request.java)工作,但是当在android程序中输入时,它每次都会抛出一个错误,当试图获取错误消息时,它只返回null Request.java package andrewmmattb.beacongame; /**
package andrewmmattb.beacongame;
/**
* Created by matt on 05/03/2016.
*/
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
public class Request {
public static void main(String[] args) throws Exception {
Request http = new Request();
System.out.println("POST");
http.sendPost("{\"username\": \"matt\",\"newPoints\":5}");
}
public static void sendPost(String json) throws Exception {
String url = "http://ec2-54-187-69-193.us-west-2.compute.amazonaws.com/points";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
String urlParameters = "";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
GameActivity.java
package andrewmmattb.beacongame;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.util.Base64;
import android.util.JsonWriter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import org.json.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
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.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class GameActivity extends Activity {
String username;
String serverPath = "THE PATH TO THE SERVER";
int score = 0;
int prevScore = 0;
TextView usernameTextView;
TextView scoreTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
usernameTextView = (TextView)findViewById(R.id.textViewGameUsername);
scoreTextView = (TextView)findViewById(R.id.textViewGameScore);
Intent intent = getIntent();
username = intent.getStringExtra("username");
usernameTextView.setText(username);
try {
makeSeverPost();
}
catch (IOException e) {
Toast.makeText(GameActivity.this,"There was an IO error, called after function call (line 56)",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
void makeSeverPost() throws IOException {
// creates a map object with username and the additional points to the previous sent score
Map<String,Object> values = new HashMap<String,Object>();
values.put("username",username);
values.put("newPoints",score-prevScore);
// sets the previous score to equal the current score
prevScore = score;
// writes the map into a string in JSON format
String jsonString = new JSONObject(values).toString();
try {
Request.sendPost(jsonString);
} catch (Exception e) {
e.printStackTrace();
Log.e("problem",""+e.getMessage());
}
}
}
package和wmmattb.beacongame;
导入android.app.Activity;
导入android.app.DownloadManager;
导入android.content.Intent;
导入android.os.Bundle;
导入android.os.Debug;
导入android.os.Handler;
导入android.util.Base64;
导入android.util.JsonWriter;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.TextView;
导入android.widget.Toast;
导入org.json.*;
导入java.io.BufferedOutputStream;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.OutputStreamWriter;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.Collection;
导入java.util.HashMap;
导入java.util.Map;
导入java.util.Set;
公共类GameActivity扩展了活动{
字符串用户名;
String serverPath=“服务器的路径”;
智力得分=0;
积分=0;
TextView用户名TextView;
文本视图;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_游戏);
usernameTextView=(TextView)findViewById(R.id.textViewGameUsername);
scoreTextView=(TextView)findViewById(R.id.textViewGameScore);
Intent=getIntent();
username=intent.getStringExtra(“用户名”);
usernameTextView.setText(用户名);
试一试{
makeSeverPost();
}
捕获(IOE异常){
Toast.makeText(GameActivity.this,“有一个IO错误,在函数调用后调用(第56行)”,Toast.LENGTH_LONG.show();
e、 printStackTrace();
}
}
void makeSeverPost()引发IOException{
//使用用户名和上一次发送的分数的附加分数创建一个映射对象
映射值=新的HashMap();
value.put(“用户名”,username);
值。put(“newPoints”,score-prevScore);
//将上一个分数设置为等于当前分数
prevScore=分数;
//将映射写入JSON格式的字符串
String jsonString=新的JSONObject(值).toString();
试一试{
sendPost(jsonString);
}捕获(例外e){
e、 printStackTrace();
Log.e(“问题”,“e.getMessage());
}
}
}
由于我们所做的所有其他尝试,存在许多冗余依赖项。在android网络中,主线程上是不允许的 您必须从
异步任务
调用此方法
例如:
class MakeSeverPostTask extends AsyncTask<Void, String, JSONObject>
{
Map<String,Object> params;
public MakeSeverPostTask(Map<String,Object> params){
this.params = params;
}
protected JSONObject doInBackground(Void... v)
{
String jsonString = new JSONObject(this.params).toString();
return Request.sendPost(jsonString);
}
protected void onPostExecute(JSONObject result)
{
}
}
类MakeSeverPostTask扩展了AsyncTask
{
映射参数;
公共MakeSeverPostTask(映射参数){
this.params=params;
}
受保护的JSONObject doInBackground(无效…v)
{
String jsonString=新的JSONObject(this.params.toString();
返回请求.sendPost(jsonString);
}
受保护的void onPostExecute(JSONObject结果)
{
}
}
用法:
Map<String,Object> values = new HashMap<String,Object>();
values.put("username",username);
values.put("newPoints",score-prevScore);
new MakeSeverPostTask(values).execute();
Map values=newhashmap();
value.put(“用户名”,username);
值。put(“newPoints”,score-prevScore);
新建MakeSeverPostTask(值).execute();
在android网络中,不允许在主线程上运行
您必须从异步任务
调用此方法
例如:
class MakeSeverPostTask extends AsyncTask<Void, String, JSONObject>
{
Map<String,Object> params;
public MakeSeverPostTask(Map<String,Object> params){
this.params = params;
}
protected JSONObject doInBackground(Void... v)
{
String jsonString = new JSONObject(this.params).toString();
return Request.sendPost(jsonString);
}
protected void onPostExecute(JSONObject result)
{
}
}
类MakeSeverPostTask扩展了AsyncTask
{
映射参数;
公共MakeSeverPostTask(映射参数){
this.params=params;
}
受保护的JSONObject doInBackground(无效…v)
{
String jsonString=新的JSONObject(this.params.toString();
返回请求.sendPost(jsonString);
}
受保护的void onPostExecute(JSONObject结果)
{
}
}
用法:
Map<String,Object> values = new HashMap<String,Object>();
values.put("username",username);
values.put("newPoints",score-prevScore);
new MakeSeverPostTask(values).execute();
Map values=newhashmap();
value.put(“用户名”,username);
值。put(“newPoints”,score-prevScore);
新建MakeSeverPostTask(值).execute();
以下是更详细的解决方案:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
usernameTextView = (TextView)findViewById(R.id.textViewGameUsername);
scoreTextView = (TextView)findViewById(R.id.textViewGameScore);
// creates a map object with username and the additional points to the previous sent score
Map<String,Object> values = new HashMap<String,Object>();
values.put("username",username);
values.put("newPoints",score-prevScore);
// writes the map into a string in JSON format
String jsonString = new JSONObject(values).toString();
String url = "http://ec2-54-187-69-193.us-west-2.compute.amazonaws.com/points";
// executing AsyncTask with passing string parameters.
ServerAsyncTask makeServerPost = new ServerAsyncTask();
makeServerPost.execute(url, jsonString);
}
private class ServerAsyncTask extends AsyncTask<String, Void, JSONObject> {
private final String TAG = ServerAsyncTask.class.getSimpleName();
@Override
protected JSONObject doInBackground(String... params) {
JSONObject result = null;
try {
URL obj = new URL(params[0]); // added url
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
String urlParameters = "";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params[1]); // Added json
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Log.i(TAG, "\nSending 'POST' request to URL : " + params[0]);
Log.i(TAG, "Post parameters : " + urlParameters);
Log.i(TAG, "Response Code : " + responseCode);
// safer way to parse response
if(responseCode == HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Log.i(TAG, response.toString());
result = new JSONObject(response.toString());
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
/* You get response jsonObject here,
you can now update your UI here*/
// Example update your score.
try {
String score = (String) jsonObject.get("score");
scoreTextView.setText(score);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@覆盖
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_游戏);
usernameTextView=(TextView)findViewById(R.id.textViewGameUsername);
scoreTextView=(TextView)findViewById(R.id.textViewGameScore);
//使用用户名和上一次发送的分数的附加分数创建一个映射对象
映射值=新的HashMap();
value.put(“用户名”,username);
值。put(“newPoints”,score-prevScore);
//将映射写入JSON格式的字符串
String jsonString=新的JSONObject(值).toString();
字符串url=”http://ec2-54-187-69-193.us-west-2.compute.amazonaws.com/points";
//使用传递的字符串参数执行AsyncTask。
ServerAsyncTask makeServerPost=新建ServerAsyncTask();
execute(url,jsonString);
}
私有类ServerAsyncTask扩展了AsyncTask{
私有最终字符串标记=ServerAsyncTask.class.getSimpleName();
@凌驾
受保护的JSONObject doInBackground(字符串…参数){
JSONObject结果=null;
试一试{
URL obj=新URL(参数[0]);//添加的URL
HttpURLConnection con=(HttpURLConnection)obj.openConnection();
//添加reuqest标题
con.setRequestMethod(“POST”);
con.setRequestProperty(“用户代理”,“用户代理”);
con.setRequestProperty(“接受语言