我在DataPackager类的此函数中有问题。
public String packData()
{
JSONObject jo=new JSONObject();
StringBuffer packedData=new StringBuffer();
try
{
jo.put("phone_number",phone);
jo.put("password",password);
Boolean firstValue=true;
int last=1;
Iterator it=jo.keys();
Log.i("Info :",jo.keys().toString());
do {
String key=it.next().toString();
String value=jo.get(key).toString();
if(firstValue)
{
firstValue=false;
//packedData.append("{");
}else
{
packedData.append(",");
last++;
}
//packedData.append('"');
packedData.append(URLEncoder.encode(key,"UTF-8"));
// packedData.append('"');
packedData.append("=");
// packedData.append('"');
packedData.append(URLEncoder.encode(value,"UTF-8"));
//packedData.append('"');
if (last==2){
//packedData.append("}");
}
}while (it.hasNext());
Log.i("Info :",packedData.toString());
return packedData.toString();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
我认为问题在于我发送到数据的json格式。我试图用这种方式格式化
{"phone_number"= "8498446545", "password"="1234"}
然后,服务器也将拒绝数据。请帮助我。
问题是格式还是代码?
MainActivity从此处开始,它向Sender类提供数据
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/*
1.OUR LAUNCHER ACTIVITY
2.INITIALIZE SOME UI STUFF
3.WE START SENDER ON BUTTON CLICK
*/
public class MainActivity extends AppCompatActivity {
String urlAddress="REST api";
EditText phoneTxt,passwordTxt;
Button saveBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//INITIALIZE UI FIELDS
phoneTxt= (EditText) findViewById(R.id.phoneText);
passwordTxt= (EditText) findViewById(R.id.passwordText);
saveBtn= (Button) findViewById(R.id.btnSave);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//START ASYNC TASK
Sender s=new
Sender(MainActivity.this,urlAddress,phoneTxt,passwordTxt);
s.execute();
}
});
}
}
这是发件人类,它扩展了AsyncTask并将数据发送到DataPackager类
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
/**
* 1.SEND DATA FROM EDITTEXT OVER THE NETWORK
* 2.DO IT IN BACKGROUND THREAD
* 3.READ RESPONSE FROM A SERVER
*/
public class Sender extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
EditText phoneTxt,passwordTxt;
String phone,password;
ProgressDialog pd;
/*
1.OUR CONSTRUCTOR
2.RECEIVE CONTEXT,URL ADDRESS AND EDITTEXTS FROM OUR MAINACTIVITY
*/
public Sender(Context c, String urlAddress,EditText...editTexts) {
this.c = c;
this.urlAddress="DRF api";
//INPUT EDITTEXTS
this.phoneTxt=editTexts[0];
this.passwordTxt=editTexts[1];
//GET TEXTS FROM EDITEXTS
phone=phoneTxt.getText().toString();
password=passwordTxt.getText().toString();
}
/*
1.SHOW PROGRESS DIALOG WHILE DOWNLOADING DATA
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Send");
pd.setMessage("Sending..Please wait");
pd.show();
}
/*
1.WHERE WE SEND DATA TO NETWORK
2.RETURNS FOR US A STRING
*/
@Override
protected String doInBackground(Void... params) {
return this.send();
}
/*
1. CALLED WHEN JOB IS OVER
2. WE DISMISS OUR PD
3.RECEIVE A STRING FROM DOINBACKGROUND
*/
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pd.dismiss();
if(response != null)
{
//SUCCESS
Toast.makeText(c,response,Toast.LENGTH_LONG).show();
phoneTxt.setText("");
passwordTxt.setText("");
}else
{
//NO SUCCESS
Toast.makeText(c,"Unsuccessful "+response,Toast.LENGTH_LONG).show();
}
}
/*
SEND DATA OVER THE NETWORK
RECEIVE AND RETURN A RESPONSE
*/
private String send()
{
//CONNECT
HttpURLConnection con=Connector.connect(urlAddress);
if(con==null)
{
return null;
}
try
{
Log.i("Info:","Connection is OK");
OutputStream os=con.getOutputStream();
//WRITE
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bw.write(new DataPackager(phone,password).packData());
Log.i("Info:","Connection is OK2222222222222");
bw.flush();
//RELEASE RES
bw.close();
os.close();
//HAS IT BEEN SUCCESSFUL?
int responseCode=con.getResponseCode();
Log.i("Response Code:",Integer.toString(responseCode));
if(responseCode==con.HTTP_OK)
{
//GET EXACT RESPONSE
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response=new StringBuffer();
Log.i("Info:","Connection is OK3333333333333333333333");
String line;
//READ LINE BY LINE
while ((line=br.readLine()) != null)
{
response.append(line);
}
//RELEASE RES
br.close();
return response.toString();
}else
{
Log.i("ERROR : ","awerstdhyigutfdrerdyugiugtfdreyuggtrdedyg");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
这是DataPackager类,它将数据打包为json格式并将其发送到连接
import android.util.Log;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
/**
* 1.BASICALLY PACKS DATA WE WANNA SEND
*/
public class DataPackager {
String phone,password;
/*
SECTION 1.RECEIVE ALL DATA WE WANNA SEND
*/
public DataPackager(String phone, String password) {
this.phone = phone;
this.password = password;
Log.i("Info :",this.phone+" "+this.password);
}
/*
SECTION 2
1.PACK THEM INTO A JSON OBJECT
1. READ ALL THIS DATA AND ENCODE IT INTO A FROMAT THAT CAN BE SENT VIA NETWORK
*/
public String packData()
{
JSONObject jo=new JSONObject();
StringBuffer packedData=new StringBuffer();
try
{
jo.put("phone_number",phone);
jo.put("password",password);
Boolean firstValue=true;
int last=1;
Iterator it=jo.keys();
Log.i("Info :",jo.keys().toString());
do {
String key=it.next().toString();
String value=jo.get(key).toString();
if(firstValue)
{
firstValue=false;
//packedData.append("{");
}else
{
packedData.append(",");
last++;
}
//packedData.append('"');
packedData.append(URLEncoder.encode(key,"UTF-8"));
// packedData.append('"');
packedData.append("=");
// packedData.append('"');
packedData.append(URLEncoder.encode(value,"UTF-8"));
//packedData.append('"');
if (last==2){
//packedData.append("}");
}
}while (it.hasNext());
Log.i("Info :",packedData.toString());
return packedData.toString();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
这是Connector类,它从DataPackager类发送数据,并检查状态是否接收到数据。在这里,我在日志中得到代码400。它指定不发送任何数据。我正在发送数据,这是不正确的。
package com.iyer.post;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Connector {
/*
1.SHALL HELP US ESTABLISH A CONNECTION TO THE NETWORK
1. WE ARE MAKING A POST REQUEST
*/
public static HttpURLConnection connect(String urlAddress) {
try
{
URL url=new URL(urlAddress);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
//SET PROPERTIES
con.setRequestMethod("POST");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
con.setDoOutput(true);
//RETURN
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}