无法使用API​​将JSON数据发布到Android服务器

时间:2016-07-25 12:00:51

标签: android

无法使用API​​

从Android发布JSON数据到服务器

这是我的gradle.build文件

apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "24.0.1"
useLibrary 'org.apache.http.legacy'
defaultConfig {
    applicationId "com.diu.mahmud.jsondataparsingstudents"
    minSdkVersion 10
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),     'proguard-rules.pro'
    }
}
}    
  dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
  compile 'com.android.support:appcompat-v7:23.4.0'
}  

这是AndroidMenifest.xml文件,这里我使用了权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.diu.mahmud.jsondataparsingstudents">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".AddNewStudent"></activity>
</application>

这是AddNewStudent.java文件 我使用了AsyncTask和所有方法

package com.diu.mahmud.jsondataparsingstudents;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class AddNewStudent extends Activity implements View.OnClickListener {

    TextView tvIsConnected;
    EditText etName,etAddress;
    Button btnPost;

    Student student;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_new_student);

    // get reference to the views
    tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
    etName = (EditText) findViewById(R.id.etName);
    etAddress = (EditText) findViewById(R.id.etAddress);

    btnPost = (Button) findViewById(R.id.btnPost);

    // check if you are connected or not
    if(isConnected()){
    tvIsConnected.setBackgroundColor(0xFF00CC00);
    tvIsConnected.setText("You are conncted");
    }
    else{
    tvIsConnected.setText("You are NOT conncted");
    }

    // add click listener to Button "POST"
    btnPost.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View view) {
    student = new Student();
    student.setName(etName.getText().toString());
    //person.setName(etName.getText().toString());
    student.setAddress(etAddress.getText().toString());
    new HttpAsyncTask().execute("http://api.diu.edu.bd/students");
    }
    });
    }

  public static String POST(String url, Student student){
    InputStream inputStream = null;
    String result = "";

    try {

    // 1. create HttpClient
    HttpClient httpclient = new DefaultHttpClient();

    // 2. make POST request to the given URL
    HttpPost httpPost = new HttpPost(url);

    String json = "";

    // 3. build jsonObject
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("name", student.getName());
    jsonObject.accumulate("address", student.getAddress());
    // 4. convert JSONObject to JSON to String
    json = jsonObject.toString();

    // ** Alternative way to convert Person object to JSON string usin Jackson Lib
    // ObjectMapper mapper = new ObjectMapper();
    // json = mapper.writeValueAsString(person);

    // 5. set json to StringEntity
    StringEntity se = new StringEntity(json);

    // 6. set httpPost Entity
    httpPost.setEntity(se);

    // 7. Set some headers to inform server about the type of the content
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");

    // 8. Execute POST request to the given URL
    HttpResponse httpResponse = httpclient.execute(httpPost);

    // 9. receive response as inputStream
    inputStream = httpResponse.getEntity().getContent();

    // 10. convert inputstream to string
    if(inputStream != null)
    result = convertInputStreamToString(inputStream);
    else
    result = "Did not work!";

    } catch (Exception e) {
    Log.d("InputStream", e.getLocalizedMessage());
    }


    return result;
    }

public boolean isConnected(){
    ConnectivityManager connMgr = (ConnectivityManager)    getSystemService(Activity.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected())
    return true;
    else
    return false;
    }
@Override
public void onClick(View view) {

    switch(view.getId()){
    case R.id.btnPost:
    if(!validate())
    Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();

    new HttpAsyncTask().execute("http://api.diu.edu.bd/students");
    break;
    }

    }
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {

    student = new Student();


    return POST(urls[0],student);
}

@Override
protected void onPostExecute(String result) {
    Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}

private boolean validate(){
    if(etName.getText().toString().trim().equals(""))
        return false;
    else if(etAddress.getText().toString().trim().equals(""))
        return false;
    else
        return true;
}

 private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;
}
}

这里是getter和setter的Student.java文件

package com.diu.mahmud.jsondataparsingstudents;

public class Student {

private String name;
private int id;
private String address;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}
}

这是activity_add_new_student.xml文件 XML代码写在这里

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/tvIsConnected"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:background="#FF0000"
    android:textColor="#FFF"
    android:textSize="18dp"
    android:layout_marginBottom="5dp"
    android:text="is connected?" />

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tvName"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:text="Name"
        android:layout_alignBaseline="@+id/etName"/>
    <EditText
        android:id="@+id/etName"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/tvName"/>
    <TextView
        android:id="@+id/tvAddress"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvName"
        android:text="Address"
        android:layout_alignBaseline="@+id/etAddress"/>
    <EditText
        android:id="@+id/etAddress"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/tvAddress"
        android:layout_below="@+id/etName"/>

 </RelativeLayout>

 <Button
    android:id="@+id/btnPost"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="POST"/>

</LinearLayout>

1 个答案:

答案 0 :(得分:0)

谢谢大家。 A解决了我的问题。 实际上我从onCreate()方法中删除了这3行并粘贴到doInBackground()中。

tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etAddress = (EditText) findViewById(R.id.etAddress);