1

将图像上传到服务器的代码:此处的完整代码

static{
    httpclient=new DefaultHttpClient();
    httpPost=new HttpPost(serverUrl);
}

public String uploadImage(String imageFileURL){

    Bitmap bitmap=BitmapFactory.decodeFile(imageFileURL);
    ByteArrayOutputStream baos=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos);
    byte []ba=baos.toByteArray();
    String bal=Base64.encodeBytes(ba);
    ArrayList<NameValuePair> nameValuePair=new ArrayList<NameValuePair>();
    nameValuePair.add(new BasicNameValuePair("image",bal));
     String res = "";
     StringBuffer buffer = new StringBuffer();
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        httpresponse=httpclient.execute(httpPost);
        httpEntity=httpresponse.getEntity();
        inputStream=httpresponse.getEntity().getContent();

        int contentLength=(int) httpresponse.getEntity().getContentLength();
        if(contentLength<0){

        }
        else{
            byte []data =new byte[512];
            int len=0;
            try{
                while(-1 !=(len=inputStream.read(data))){
                    buffer.append(new String(data,0,len));
                }

            }
            catch(IOException e){
                e.printStackTrace();
                return null;
            }
        }

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally{
        try {
            inputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    res=buffer.toString();
    return res; 
}

正在调用此方法

 onClick(View view){
    new Thread(new Runnable(){

        public void run() {
            // TODO Auto-generated method stub
            response=new ServerCommunication().uploadImage(path);
        }           
    }).start();

但它显示为TimeOutException。谁能告诉我我做错了什么。

4

1 回答 1

0

添加此代码以删除超时异常:

final int TIMEOUT_MILLISEC = 20000;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
于 2012-10-17T11:11:26.553 回答