2013-03-17 59 views
0

我試圖使用Android的POST請求,但我沒有成功。我認爲問題在於如何設置resquisição和Header的參數。下面是我的方法,我做的請求......發送json在android中的發佈日期與參數

public void testPostDate() { 

    HttpClient client = new DefaultHttpClient(); 
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); 
    HttpResponse response; 

    Gson gson = new Gson(); 
    CrimePOST.Crime crime = new CrimePOST().new Crime(10, "São Paulo", 
      "descrição", 10.00, 30.00); 

    CrimePOST crimePost = new CrimePOST(); 
    crimePost.setCrime(crime); 

    List<NameValuePair> params = new LinkedList<NameValuePair>(); 

    params.add(new BasicNameValuePair("token", 
      "0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJa6JhMs=")); 

    String json = gson.toJson(crimePost); 

    String paramString = URLEncodedUtils.format(params, Utils.ENCODE); 

    try { 
     HttpPost post = new HttpPost(
       "http://safe-sea-4024.herokuapp.com/crimes/mobilecreate" 
         + "?" + paramString); 

     post.setHeader("Content-Type", "application/json"); 

     StringEntity entitty = new StringEntity(json); 
     entitty.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, 
       "application/json")); 

     post.setEntity(entitty); 
     response = client.execute(post); 

     /* Checking response */ 
     if (response != null) { 
      InputStream in = response.getEntity().getContent(); 
      String a = toString(in); 
      System.out.println(a); 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

這種方法是負責一個InputStream轉換爲字符串

private String toString(InputStream is) throws IOException { 

    byte[] bytes = new byte[1024]; 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    int lidos; 
    while ((lidos = is.read(bytes)) > 0) { 
     baos.write(bytes, 0, lidos); 
    } 
    return new String(baos.toByteArray()); 
} 

真的我正確地傳遞頭?

回答

1

您必須在AsyncTask中執行此操作

+0

這是一個測試方法,因此並不需要的AsyncTask。 – 2013-03-17 01:35:42

+0

這是一個重要的信息。我不知道單元測試如何在android中工作。但是,錯誤信息是什麼? – micho 2013-03-17 01:37:00

+0

我連接成功。但是,我的服務器返回一個錯誤,告訴我它需要設置一個Content Headers。我可能會採用錯誤的方式Content Headers :( – 2013-03-17 01:44:03

1

我在回寫本教程時寫道。它確實通過HTTP Post發送json數據到一個url。一探究竟。原帖可以在這裏找到:http://androidhappenings.blogspot.com/2013/03/android-app-development-201-1st.html

import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.util.Timer; 
import java.util.TimerTask; 
import org.apache.http.client.ClientProtocolException; 
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.JSONException; 
import org.json.JSONObject; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Handler; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 


public class MainActivity extends Activity implements LocationListener{ 
private TextView textView =null; 
LocationManager locationManager=null; 
Location location=null; 
protected String url; 
protected JSONObject jsonData=null; 
private EditText urlText=null; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    if(gpsEnabled!=true) { 
     Toast.makeText(getApplicationContext(), "GPS Disbled! Please Enable to Proceed!", Toast.LENGTH_SHORT).show(); 
     startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
    } 

    textView = (TextView)findViewById(R.id.textView); 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, this); 
    urlText = (EditText)findViewById(R.id.urlTextbox); 
    Button submitButton = (Button)findViewById(R.id.submitUrl); 

    submitButton.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      if (urlText.getText()!=null) { 
      url=urlText.getText().toString(); 
      System.out.println(url);//for testing only, not required 
      Toast.makeText(getApplicationContext(), "Url Submitted, Sending data to Web Service at url: " + url, Toast.LENGTH_SHORT).show(); 
     } 
     } 
    }); 




} 

@Override 
public void onLocationChanged(final Location location) { 
    this.location=location; 
    final Handler handler = new Handler(); 
     Timer ourtimer = new Timer(); 
     TimerTask timerTask = new TimerTask() { 
      int cnt=1;  
      public void run() { 
         handler.post(new Runnable() { 
           public void run() { 

           Double latitude = location.getLatitude(); 
           Double longitude = location.getLongitude(); 
           Double altitude = location.getAltitude(); 
           Float accuracy = location.getAccuracy(); 
           textView.setText("Latitude: " + latitude + "\n" + "Longitude: " + longitude+ "\n" + "Altitude: " + altitude + "\n" + "Accuracy: " + accuracy + "meters"+"\n" + "Location Counter: " + cnt); 
          try { 
           jsonData = new JSONObject(); 
           jsonData.put("Latitude", latitude); 
           jsonData.put("Longitude", longitude); 
           jsonData.put("Altitude", altitude); 
           jsonData.put("Accuracy", accuracy); 

           System.out.println(jsonData.toString());//not required, for testing only 
           if(url!=null) { 
           new HttpPostHandler().execute(); 
           } 
          } catch (JSONException e) { 
           // TODO Auto-generated catch block 
           e.printStackTrace(); 
          } 

           cnt++; 
           } 

        }); 
       }}; 
      ourtimer.schedule(timerTask, 0, 120000); 

} 

@Override 
public void onProviderDisabled(String provider) { 


} 

@Override 
public void onProviderEnabled(String provider) { 


} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 


} 





public class HttpPostHandler extends AsyncTask<Void,Void,Void> { 

@Override 
protected Void doInBackground(Void... arg0) { 

    HttpClient httpClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(url); 
    StringEntity dataEntity = null; 
    try { 
     dataEntity = new StringEntity(jsonData.toString()); 
    } catch (UnsupportedEncodingException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    httpPost.setEntity(dataEntity); 
    httpPost.setHeader("Content-Type", "application/json"); 
    try { 
     httpClient.execute(httpPost); 
    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 

    } 
    return null; 


} 

@Override 
protected void onPostExecute(Void result) { 
    // TODO Auto-generated method stub 
    super.onPostExecute(result); 
    try { 
     this.finalize(); 
    } catch (Throwable e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

} 

}