2014-02-18 3 views
0

나는 안드로이드에 익숙하지 않으며 http 게시 요청을하려고하는데 다음과 같은 오류가 발생합니다. 내 코드와 LogCat 일부 줄을 게시했습니다. 다른 클래스에서이 작업을 수행해야합니까, 그렇다면 어떻게해야할까요, 아니면 현재 코드에서 수정해야하는 작업 일 수 있습니다.Http Post 다른 스레드에서 안드로이드를 요청합니다.

public class PasteCode extends Activity { 

@Override 

protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.pastecode); 

    final EditText codeinput = (EditText) findViewById(R.id.editText1); 

    Button send_btn = (Button) findViewById(R.id.button1); 
    send_btn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      final String code = codeinput.getText().toString(); 

      new Thread(new Runnable() { 
       @Override 
       public void run() { 

        HttpClient httpClient = new DefaultHttpClient(); 
        HttpPost httpPost = new HttpPost("accounts.google.com"); 

        ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5); 
        nameValuePair.add(new BasicNameValuePair("code", code)); 
        nameValuePair.add(new BasicNameValuePair("client_id", "----------------------")); 
        nameValuePair.add(new BasicNameValuePair("client_secret", "-----------------")); 
        nameValuePair.add(new BasicNameValuePair("redirect_uri", "urn:ietf:wg:oauth:2.0:oob")); 
        nameValuePair.add(new BasicNameValuePair("grant_type", "authorization_code")); 

        try { 
         httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 

        } catch (UnsupportedEncodingException e) { 
         // writing error to Log 
         e.printStackTrace(); 
        } 

        // Making HTTP Request 
        try { 
         HttpResponse response = httpClient.execute(httpPost); 

         // writing response to log 
         Log.d("Http Response:", response.toString()); 
        } catch (ClientProtocolException e) { 
         // writing exception to log 
         e.printStackTrace(); 
        } catch (IOException e) { 
         // writing exception to log 
         e.printStackTrace(); 

        } 

       } 
      }).start(); 
     } 
    }); 
} 
} 

LogView의

02-18 10 : 03 : 20.477 : W/dalvikvm (3759)는 : threadid = 15 : 스레드 캐치되지 않는 예외 (그룹 = 0x4001d760)

02-18으로 출사 10 : 03 : 20.487 : 치명적인 예외 : 스레드 (31)

10월 2일부터 18일까지 : 03 : 20.487 : (3759) E는/AndroidRuntime E는/AndroidRuntime (3759) : java.lang.IllegalStateException는 : 호스트 대상이되지해야합니다 null 또는 매개 변수로 설정하십시오. 방식 = NULL 호스트 = NULL, 경로 = accounts.google.com

10월 2일부터 18일까지 : 03 : 20.487 : E/AndroidRuntime (3759) java.lang.Thread.run (Thread.java에서 : 1020)

답변

-1

안녕하세요. 좋은 아침에 logcat 오류를 게시 해주세요. 제발 ... 실제로 안드로이드는 앱의 메인 스레드에서 http 요청을하도록 허용하지 않습니다 ... 당신이 찾고있는 것을 성취 할 수있는 몇 가지 방법이 있습니다 for ... 먼저 asyncTask ...로 쓰레드를 구현할 수 있습니다. 또는 단지 목적을 개발하기 위해 폴리 라인을 제거 할 수 있습니다.이 라인을 액티비티의 onCreate에서 코드에 추가 할 수 있습니다 ...

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
    StrictMode.setThreadPolicy(policy); 

하지만이 사용하지 않는 것이 좋습니다 ...

편집 :

확인 당신은 당신이 가지고있는 코드를 게시하시기 바랍니다 수 ... 당신의 오류가 더 데이터베이스 또는 당신이 보내는 데이터를 처리 할 수있는 아무것도 없다 참조 서버 측에서 ... 또한 데이터를 보내는 URL을 확인하십시오 ... 유효하지 않은 것으로 보입니다 ...이 작업을 수행하는 방법을 보여주는 한 가지 예를 게시 할 것입니다 .. !!

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); 
     nameValuePairs.add(new BasicNameValuePair("data1", "data")); 
     nameValuePairs.add(new BasicNameValuePair("data2", "dataa")); 
     nameValuePairs.add(new BasicNameValuePair("data3", "dataaa")); 
     try { 
      res = CustomHttpClient.sendData("URL", nameValuePairs); 
      String resp = res.toString(); 
      Log.e(Tag, res); 
      resp = resp.replaceAll("\\s+",""); 

당신은 내가 정의 HTTP 클라이언트의 인스턴스를 만드는 중이라서 참조 서버에 전화를 걸 수있는 담당 한 이십 기가 바이트 ... 그리고 서버에서 응답을 처리하는 담당도 수 ...

공용 클래스 CustomHttpClient {

public static final int HTTP_TIMEOT = 30 * 1000; 
private static HttpClient mHttpClient; 

private static HttpClient getHttpClient() { 
    if (mHttpClient == null) ; 
    { 
     mHttpClient = new DefaultHttpClient(); 
     final HttpParams param = mHttpClient.getParams(); 
     HttpConnectionParams.setConnectionTimeout(param, HTTP_TIMEOT); 
     HttpConnectionParams.setSoTimeout(param, HTTP_TIMEOT); 
     ConnManagerParams.setTimeout(param, HTTP_TIMEOT); 
    } 
    return mHttpClient; 
} 

public static String sendData(String url, ArrayList nameValuePairs) throws Exception { 
    BufferedReader reader = null; 
    try { 
     HttpClient httpclient = getHttpClient(); 
     HttpPost httppost = new HttpPost(url); 
     UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs); 
     httppost.setEntity(formEntity); 

     HttpResponse response = httpclient.execute(httppost); 
     reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     StringBuffer sBuffer = new StringBuffer(""); 
     String line = ""; 
     String NL = System.getProperty("line.separator"); 
     while ((line = reader.readLine()) != null) { 
      sBuffer.append(line + NL); 
     } 
     reader.close(); 
     String result = sBuffer.toString(); 
     return result; 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

}

그는 별도의 스레드를 사용
+0

!!!! – Merlevede

+0

"http : //"를 경로 이름에 추가하여이 오류를 해결했지만 이제는 내가 얻은 응답을 읽으려고 애 쓰고 있습니다. – user3271572

+0

기다리고있는 응답은 무엇입니까 ??? 좀 더 구체적으로 좀 주시겠습니까 ?? – geekCode